Convenience constructors

By now you have probably noticed in the class documentation that most Cocoa classes have a set of class methods that are named in the format +className.... These special class methods are called "convenience constructors," and are used to create temporary objects. What I mean by temporary is that objects returned by a convenience constructor are assumed to be autoreleased, and are thus valid only within the method that uses the convenience constructor.

An example of one of the many convenience constructors available is the NSString method, +stringWithCString:. We can use this method instead of creating an NSString instance using the usual alloc/init process. For example, consider the following code that uses alloc and init:

NSString *string = [[NSString alloc] initWithCString:"Hello"];
[textField setStringValue:string];
[string release];

This can be shortened using a convenience constructor:

NSString *string = [NSString stringWithCString:"Hello"];
[textField setStringValue:string];
// don't need to release string since objects
// returned by convenience constructors are
// assumed to be autoreleased.
Convenience constructors also make it less cumbersome to nest messages:

[textField setStringValue:[NSString stringWithCString:"Hello]];

So, if you need a string (or any other object) to exist only within a method, it's often easier, cleaner, and more readable to use a convenience constructor.

If you want to set an instance variable using a convenience constructor, you have to send it a retain message so that it is not released when the autorelease pool is cleared out, like so:

// assume stringInstanceVariable exists
stringInstanceVariable = [[NSString stringWithCString:"Hello"] retain];

retain is a way to assess object ownership on objects that you didn't initially create, so this extends our rule of matching every alloc with a release or autorelease, and now we also have to match any retain messages with release or autorelease.

Enviar um comentário

About This Blog

  © Blogger template Shush by Ourblogtemplates.com 2009

Back to TOP