I am having a hard time figuring out when to alloc an object. I am going through the Apress iPhone Dev for Beginners book. Sometimes it says use:
UIImage *seven = [UIImage imageNamed:@"seven.png"];
and other times,
UIImageView *sevenView = [[UIImageView alloc] initWithImage:seven];
Why don't you alloc UIImage in the first example?
Thanks - Absolute Beginner.
These values are guaranteed after the alloc method is called. However, that object is not quite ready to use yet—it has to be initialized first (otherwise strange bugs are mostly guaranteed). This is accomplished by the init instance method, which is often overridden.
It’s a superset of the C programming language and provides object-oriented capabilities and a dynamic runtime. Objective-C inherits the syntax, primitive types, and flow control statements of C and adds syntax for defining classes and methods.
They also have syntax restrictions—the method must not return anything (that’- how it becomes a constructor), it must have the same name as the class, any call to super must be the first statement… Objective-C has none of these restrictions.
It is important that you nest the alloc and init methods—there are instances where the initialization method may not return the same object as was allocated. This is true when working with classes such as NSString, which are in fact a public interface for a variety of classes.
initWithImage:
is an instance method - the message must be sent to a particular object. You create such an object instance with alloc
.
imageNamed:
is a class method. It does not need to be sent to an instance of the class, so you don't allocate an object. Such methods returning objects will often allocate and init an object "under the hood".
You can find the information which methods are class methods and which are instance methods in the class reference. Also, class method declarations start with +
as in + (UIImage *)imageNamed:(NSString *)name
, instance methods with -
as in - (id)initWithData:(NSData *)data
.
By the way, alloc
is just a class method of NSObject
.
The convention is that whenever you call [Foo alloc], you have to [release] the resulting Foo object afterwards. On the other hand, if the method is called [fooWithBar], or something similar, it returns an autoreleased object, the one that will be autoreleased when the current system-called function returns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With