Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Objective C, when is alloc used and when is it no

Tags:

objective-c

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.

like image 843
David Avatar asked May 06 '11 22:05

David


People also ask

When are the values guaranteed by the alloc method?

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.

What is Objective-C?

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.

What are the syntax restrictions in Objective-C?

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.

Why is it important to nest The alloc and init methods?

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.


2 Answers

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.

like image 98
Rüdiger Hanke Avatar answered Sep 20 '22 05:09

Rüdiger Hanke


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.

like image 42
Seva Alekseyev Avatar answered Sep 20 '22 05:09

Seva Alekseyev