Top cocoa-touch Questions

List of Tags

I have a UILabel with space for two lines of text. Sometimes, when the text is too short, this text is displayed in the vertical center of the label.

How do I vertically align my text to be always at the top of the UILabel?

alt text

Answered By: nevan king ( 850)

There's no way to set the vertical align on a UILabel, but you can get the same effect by changing the label's frame. I've made my labels orange so you can see clearly what's happening.

Here's the quick and easy way to do this:

    [myLabel sizeToFit];

sizeToFit to squeeze a label

If you have a label with longer text that will make more than one line, set numberOfLines to 0 (zero here means an unlimited number of lines).

    myLabel.numberOfLines = 0;
    [myLabel sizeToFit];

Longer label text with sizeToFit

Longer Version

I'll make my label in code so that you can see what's going on. You can set up most of this in Interface Builder too. My setup is a View Based App with a background image I made in Photoshop to show margins (20 points). The label is an attractive orange color so you can see what's going on with the dimensions.

- (void)viewDidLoad
    [super viewDidLoad];

    // 20 point top and left margin. Sized to leave 20 pt at right.
    CGRect labelFrame = CGRectMake(20, 20, 280, 150);
    UILabel *myLabel = [[UILabel alloc] initWithFrame:labelFrame];
    [myLabel setBackgroundColor:[UIColor orangeColor]];

    NSString *labelText = @"I am the very model of a modern Major-General, I've information vegetable, animal, and mineral";
    [myLabel setText:labelText];

    // Tell the label to use an unlimited number of lines
    [myLabel setNumberOfLines:0];
    [myLabel sizeToFit];

    [self.view addSubview:myLabel];

Some limitations of using sizeToFit come into play with center- or right-aligned text. Here's what happens:

    // myLabel.textAlignment = UITextAlignmentRight;
    myLabel.textAlignment = UITextAlignmentCenter;

    [myLabel setNumberOfLines:0];
    [myLabel sizeToFit];

enter image description here

The label is still sized with a fixed top-left corner. You can save the original label's width in a variable and set it after sizeToFit, or give it a fixed width to counter these problems:

    myLabel.textAlignment = UITextAlignmentCenter;

    [myLabel setNumberOfLines:0];
    [myLabel sizeToFit];

    CGRect myFrame = myLabel.frame;
    // Resize the frame's width to 280 (320 - margins)
    // width could also be myOriginalLabelFrame.size.width
    myFrame = CGRectMake(myFrame.origin.x, myFrame.origin.y, 280, myFrame.size.height);
    myLabel.frame = myFrame;

label alignment

Note that sizeToFit will respect your initial label's minimum width. If you start with a label 100 wide and call sizeToFit on it, it will give you back a (possibly very tall) label with 100 (or a little less) width. You might want to set your label to the minimum width you want before resizing.

Correct label alignment by resizing the frame width

Some other things to note:

Whether lineBreakMode is respected depends on how it's set. UILineBreakModeTailTruncation (the default) is ignored after sizeToFit, as are the other two truncation modes (head and middle). UILineBreakModeClip is also ignored. UILineBreakModeCharacterWrap works as usual. The frame width is still narrowed to fit to the rightmost letter.

My Original Answer (for posterity/reference):

This uses the NSString method sizeWithFont:constrainedToSize:lineBreakMode: to calculate the frame height needed to fit a string, then sets the origin and width.

Resize the frame for the label using the text you want to insert. That way you can accommodate any number of lines.

CGSize maximumSize = CGSizeMake(300, 9999);
NSString *dateString = @"The date today is January 1st, 1999";
UIFont *dateFont = [UIFont fontWithName:@"Helvetica" size:14];
CGSize dateStringSize = [dateString sizeWithFont:dateFont 

CGRect dateFrame = CGRectMake(10, 10, 300, dateStringSize.height);

self.dateLabel.frame = dateFrame;

This page has some different code for the same solution:

I would like to check to see if I have an Internet connection on the iPhone using the Cocoa Touch libraries.

I came up with a way to do this using an NSURL. The way I did it seems a bit unreliable (because even Google could one day be down and relying on a 3rd party seems bad) and while I could check to see for a response from some other websites if Google didn't respond, it does seem wasteful and an unnecessary overhead on my application.

- (BOOL) connectedToInternet
    NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@""]];
    return ( URLString != NULL ) ? YES : NO;

Is what I have done bad? (Not to mention stringWithContentsOfURL is deprecated in 3.0) And if so what is a better way to accomplish this?

Answered By: iWasRobbed ( 528)

Use a simple library to do it: (ARC and GCD Compatible Reachability)

OR... Do it yourself:

1) Add SystemConfiguration framework to the project but don't worry about including it anywhere

2) Add Reachability.h and Reachability.m to the project (you can get those here)

3) Add @class Reachability; to the .h file of where you are implementing the code

4) Create a couple instances to check in the interface section of the .h file:

Reachability* internetReachable;
Reachability* hostReachable;

5) Add a method in the .h for when the network status updates:

-(void) checkNetworkStatus:(NSNotification *)notice;

6) Add #import "Reachability.h" to the .m file where you are implementing the check

7) In the .m file of where you are implementing the check, you can place this in one of the first methods called (init or viewWillAppear or viewDidLoad etc):

-(void) viewWillAppear:(BOOL)animated
    // check for internet connection
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];

    internetReachable = [[Reachability reachabilityForInternetConnection] retain];
    [internetReachable startNotifier];

    // check if a pathway to a random host exists
    hostReachable = [[Reachability reachabilityWithHostName: @""] retain];
    [hostReachable startNotifier];

    // now patiently wait for the notification

8) Set up the method for when the notification gets sent and set whatever checks or call whatever methods you may have set up (in my case, I just set a BOOL)

-(void) checkNetworkStatus:(NSNotification *)notice
    // called after network status changes
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
    switch (internetStatus)
        case NotReachable:
            NSLog(@"The internet is down.");
            self.internetActive = NO;

        case ReachableViaWiFi:
            NSLog(@"The internet is working via WIFI.");
            self.internetActive = YES;

        case ReachableViaWWAN:
            NSLog(@"The internet is working via WWAN.");
            self.internetActive = YES;


    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
    switch (hostStatus)
        case NotReachable:
            NSLog(@"A gateway to the host server is down.");
            self.hostActive = NO;

        case ReachableViaWiFi:
            NSLog(@"A gateway to the host server is working via WIFI.");
            self.hostActive = YES;

        case ReachableViaWWAN:
            NSLog(@"A gateway to the host server is working via WWAN.");
            self.hostActive = YES;


9) In your dealloc or viewWillDisappear or similar method, remove yourself as an observer

-(void) viewWillDisappear:(BOOL)animated
    [[NSNotificationCenter defaultCenter] removeObserver:self];

Note: There might be an instance using viewWillDisappear where you receive a memory warning and the observer never gets unregistered so you should account for that as well.


It is to my understanding that one should use a forward-class declaration in the event ClassA needs to include a ClassB header, and ClassB needs to include a ClassA header to avoid any circular inclusions. I also understand that an #import it a simple ifndefso that an include only happens.

My inquiry is this: When does one use #import and when does one use @class? Sometimes if I use a @class declaration, I see a common compiler warning such as the following:

warning: receiver 'FooController' is a forward class and corresponding @interface may not exist.

Would really love to understand this, versus just removing the @class forward-declaration and throwing an #import in to silence the warnings the compiler is giving me.

Answered By: Ben Gottlieb ( 459)

If you see this warning:

warning: receiver 'myCoolClass' is a forward class and corresponding @interface may not exist

you need to #import the file, but you can do that in your implementation file (.m), and use the @class declaration in your header file.

@class does not (usually) remove the need to #import files, it just moves the requirement down closer to where the information is useful.

For Example

If you say @class myCoolClass, the compiler knows that it may see something like:

myCoolClass *myObject;

It doesn't have to worry about anything other than myCoolClass is a valid class, and it should reserve room for a pointer to it (really, just a pointer). Thus, in your header, @class suffices 90% of the time.

However, if you ever need to create or access myObject's members, you'll need to let the compiler know what those methods are. At this point (presumably in your implementation file), you'll need to #import "myCoolClass.h", to tell the compiler additional information beyond just "this is a class".

I know about the HIG (which is quite handy!), but what programming practices do you use when writing Objective-C, and more specifically when using Cocoa (or CocoaTouch).

Answered By: Kendall Helmstetter Gelner ( 400)

There are a few things I have started to do that I do not think are standard:

1) With the advent of properties, I no longer use "_" to prefix "private" class variables. After all, if a variable can be accessed by other classes shouldn't there be a property for it? I always disliked the "_" prefix for making code uglier, and now I can leave it out.

2) Speaking of private things, I prefer to place private method definitions within the .m file in a class extension like so:

#import "MyClass.h"

@interface MyClass ()
- (void) someMethod;
- (void) someOtherMethod;

@implementation MyClass

Why clutter up the .h file with things outsiders should not care about? The empty () works for private categories in the .m file, and issues compile warnings if you do not implement the methods declared.

3) I have taken to putting dealloc at the top of the .m file, just below the @synthesize directives. Shouldn't what you dealloc be at the top of the list of things you want to think about in a class? That is especially true in an environment like the iPhone.

3.5) In table cells, make every element (including the cell itself) opaque for performance. That means setting the appropriate background color in everything.

3.6) When using an NSURLConnection, as a rule you may well want to implement the delegate method:

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse *)cachedResponse
      return nil;

I find most web calls are very singular and it's more the exception than the rule you'll be wanting responses cached, especially for web service calls. Implementing the method as shown disables caching of responses.

Also of interest, are some good iPhone specific tips from Joseph Mattiello (received in an iPhone mailing list). There are more, but these were the most generally useful I thought (note that a few bits have now been slightly edited from the original to include details offered in responses):

4) Only use double precision if you have to, such as when working with CoreLocation. Make sure you end your constants in 'f' to make gcc store them as floats.

float val = someFloat * 2.2f;

This is mostly important when someFloat may actually be a double, you don't need the mixed-mode math, since you're losing precision in 'val' on storage. While floating-point numbers are supported in hardware on iPhones, it may still take more time to do double-precision arithmetic as opposed to single precision. References:

On the older phones supposedly calculations operate at the same speed but you can have more single precision components in registers than doubles, so for many calculations single precision will end up being faster.

5) Set your properties as nonatomic. They're atomic by default and upon synthesis, semaphore code will be created to prevent multi-threading problems. 99% of you probably don't need to worry about this and the code is much less bloated and more memory-efficient when set to nonatomic.

6) SQLite can be a very, very fast way to cache large data sets. A map application for instance can cache its tiles into SQLite files. The most expensive part is disk I/O. Avoid many small writes by sending BEGIN; and COMMIT; between large blocks. We use a 2 second timer for instance that resets on each new submit. When it expires, we send COMMIT; , which causes all your writes to go in one large chunk. SQLite stores transaction data to disk and doing this Begin/End wrapping avoids creation of many transaction files, grouping all of the transactions into one file.

Also, SQL will block your GUI if it's on your main thread. If you have a very long query, It's a good idea to store your queries as static objects, and run your SQL on a separate thread. Make sure to wrap anything that modifies the database for query strings in @synchronize() {} blocks. For short queries just leave things on the main thread for easier convenience.

More SQLite optimization tips are here, though the document appears out of date many of the points are probably still good;

What I want to do seems pretty simple, but I can't find any answers on the web. I have an NSMutableArray of objects, let's say they are 'Person' objects. I want to sort the NSMutableArray by Person.birthDate which is an NSDate.

I think it has something to do with this method:

NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(???)];

In Java I would make my object implement Comparable, or use Collections.sort with an inline custom on earth do you do this in Objective-C?

Answered By: Georg Schölly ( 720)

Compare method

Either you implement a compare-method for your object:

- (NSComparisonResult)compare:(Person *)otherObject {
    return [self.birthDate compare:otherObject.birthDate];

NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];

NSSortDescriptor (better)

or usually even better:

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate"
                                              ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];

You can easily sort by multiple keys by adding more than one to the array. Using custom comparator-methods is possible as well. Have a look at the documentation.

Blocks (shiny!)

There's also the possibility of sorting with a block since Mac OS X 10.6 and iOS 4:

NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    NSDate *first = [(Person*)a birthDate];
    NSDate *second = [(Person*)b birthDate];
    return [first compare:second];
Airsource Ltd

I would like to have an app include a custom font for rendering text, load it, and then use it with standard UIKit elements like UILabel. Is this possible?

I found these links:

but these would require me to render each glyph myself, which is a bit too much like hard work, especially for multi-line text.

I've also found posts that say straight out that it's not possible, but without justification, so I'm looking for a definitive answer.

EDIT - failed -[UIFont fontWithName:size:] experiment

I downloaded Harrowprint.tff (downloaded from here) and added it to my Resources directory and to the project. I then tried this code:

UIFont* font = [UIFont fontWithName:@"Harrowprint" size:20];

which resulted in an exception being thrown. Looking at the TTF file in Finder confirmed that the font name was Harrowprint.

EDIT - there have been a number of replies so far which tell me to read the documentation on X or Y. I've experimented extensively with all of these, and got nowhere. In one case, X turned out to be relevant only on OS X, not on iPhone. Consequently I am setting a bounty for this question, and I will award the bounty to the first person who provides an answer (using only documented APIs) who responds with sufficient information to get this working on the device. Working on the simulator too would be a bonus.

EDIT - it appears that the bounty auto-awards to the answer with the highest nunber of votes. Interesting. No one actually provided an answer that solved the question as asked - the solution that involves coding your own UILabel subclass doesn't support word-wrap, which is an essential feature for me - though I guess I could extend it to do so.

Answered By: commanda ( 167)

Edit: As of iOS 3.2, this functionality is built in. If you need to support pre-3.2, you can still use this solution.

I created a simple module that extends UILabel and handles loading .ttf files. I released it opensource under the Apache license and put it on github here: git://

The important files are FontLabel.h and FontLabel.m.

It uses some of the code from Genericrich's answer above.

Browse the source here:

When you tap a row in a UITableView, the row is highlighted and selected. Is it possible to disable this so tapping a row does nothing?

Answered By: Martin Gordon ( 515)

All you have to do is set the selection style on the UITableViewCell instance using either:

cell.selectionStyle = UITableViewCellSelectionStyleNone;


[cell setSelectionStyle:UITableViewCellSelectionStyleNone];

Further, make sure you either don't implement -tableView:didSelectRowAtIndexPath: in your table view delegate or explicitly exclude the cells you want to have no action if you do implement it.

More info here and here

I'm doing a presentation on debugging in Xcode and would like to get more information on using NSLog efficiently.

In particular, I have two questions:

  • is there a way to easily NSLog the current method's name / line number?
  • is there a way to "disable" all NSLogs easily before compiling for release code?
Answered By: Diederik Hoogenboom ( 300)

Here are some useful macros around NSLog I use a lot:

#ifdef DEBUG
#   define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#   define DLog(...)

// ALog always displays output regardless of the DEBUG setting
#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)

The DLog macro is used to only output when the DEBUG variable is set (-DDEBUG in the projects's C flags for the debug confirguration).

ALog will always output text (like the regular NSLog).

The output (e.g. ALog(@"Hello world") ) will look like this:

-[LibraryController awakeFromNib] [Line 364] Hello world

Does anybody know if it's possible, and how, to programmatically send a SMS from the iPhone, with the official SDK / Cocoa Touch?

Answered By: Adam Davis ( 152)


If you could send an SMS within a program on the iPhone, you'll be able to write games that spam people in the background. I'm sure you really want to have spams from your friends, "Try out this new game! It roxxers my boxxers, and yours will be too!!!!! If you sign up now you'll get 3,200 RB points!!"

Apple has restrictions for automated (or even partially automated) SMS and dialing operations. (Imagine if the game instead dialed 911 at a particular time of day)

Your best bet is to setup an intermediate server on the internet that uses an online SMS sending service, and send the SMSs via that route if you need complete automation. (ie, your program on the iPhone sends a UDP packet to your server, which sends the real SMS)

iOS 4 Update

iOS 4, however, now provides a viewcontroller you can import into your application. You prepopulate the SMS fields, then the user can initiate the SMS send within the controller. Unlike using the "sms:..." url format, this allows your application to stay open, and allows you to populate both the to and the body fields. You can even specify multiple recipients.

This prevents applications from sending automated SMS without the user explicitly aware of it. You still cannot send fully automated SMS from the iPhone itself, it requires some user interaction. But this at least allows you to populate everything, and avoids closing the application.

The MFMessageComposeViewController class is well documented, and tutorials show how easy it is to implement.

iOS 5 Update

iOS 5 includes messaging for iPod touch and iPad devices, so while I've not yet tested this myself, it may be that all iOS devices will be able to send SMS via MFMessageComposeViewController. If this is the case, then Apple is running an SMS server that sends messages on behalf of devices that don't have a cellular modem.

Limitations to this class

Keep in mind that this won't work on phones without iOS 4, and it won't work on the iPod touch or the iPad, except, perhaps, under iOS 5. You must either detect the device and iOS limitations prior to using this controller, or risk restricting your app to recently upgraded 3G, 3GS, and 4 iPhones.

However, an intermediate server that sends SMS will allow any and all of these iOS devices to send SMS as long as they have internet access, so it may still be a better solution for many applications. Alternately, use both, and only fall back to an online SMS service when the device doesn't support it.

What are the differences between implementing a @property with @dynamic or @synthesize??


Answered By: Diederik Hoogenboom ( 255)

@synthesize will generate getter and setter methods for your property. @dynamic just tells the compiler that the getter and setter methods are implemented not by the class itself but somewhere else (like the superclass)

Uses for @dynamic are e.g. with subclasses of NSManagedObject (CoreData) or when you want to create an outlet for a property defined by a superclass that was not defined as an outlet:

Super class:

@property (nonatomic, retain) NSButton *someButton;
@synthesize someButton;


@property (nonatomic, retain) IBOutlet NSButton *someButton;
@dynamic someButton;