Reputation: 71
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.
Upvotes: 7
Views: 504
Reputation: 6255
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
.
Upvotes: 9
Reputation: 2499
A good rule of thumb is that you want to use -alloc when you know your object is going to be holding on to that object for a long time, or when you're creating an object that will never need to leave the scope of the method in which it's created- in both cases, you can avoid the (albeit small) overhead that autoreleasing an object brings, and know that you're minimizing your memory footprint- by default, autoreleased objects won't actually be freed until the next run loop, which could be considerably far in the future.
That being said, using convenience methods often make it easier to produce an object with certain conditions, and autoreleased objects in general are very useful for returning objects up the stack.
Upvotes: 0
Reputation: 2421
This can be confusing at the start. In your above examples, the [UIImage imageNamed]
method is a static convenience method that the creators of the API decided would be helpful. Under the covers that method will return to you an autoreleased object of type UIImage
.
As you use the Cocoa Touch API's you will become more familiar with them and convenience using functions, etc, will feel more natural.
Note: In the two cases you outlined above, one will give you a autoreleased UIImage and the second will give you a UIImageView that you have to specifically release when you want to relinquish ownership of the object (or you will get a memory leak).
For some info on UIImage vs UIImageView have a look at this thread.
Upvotes: 0
Reputation: 61398
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.
Upvotes: 2