Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

ptaylor9

macrumors member
Original poster
Sep 16, 2009
53
0
Hi,
I have just come back to my Objective-C book, and something that I thought I had nailed a few weeks ago seems to have escaped my mind.
I know this is going to risk me sounding stupid, but I am going to go for it anyway.

Looking at NSArray objects as an example (and NSDictionary objects too), they both have methods such as
+(id)arrayWithCapacity size; or +(id)dictionaryWithObjectsAndKeys
-(id)initWithCapacity size; or -(id)initWithOjectsAndKeys

Could someone just explain to mean in simple English when the class method should be used, and when the instance method should be used.
I think it is related to what the created object is 'owned' by, and whether it needs manually releasing from memory, but i'm going round in circles and its doing my head in.

Hopefully some friendly passing MacRumors guru can sort me out once and for all. I plan to go through the book again from scratch hen I have covered most things, and pick up the stuff i missed.
Cheers
P.
 
Class methods (+) should be called on a class itself.

For example
NSMutableArray *array = [NSMutableArray array]; \\ returns an empty array


Instance methods are called on instances of classes (-)
int count = [array count]; \\ returns how many objects are in the array


The reason people get confused with init(whatever) is that the "hidden" method +alloc is a class method for everything that inherits from NSObject

NSArray *array = [NSArray alloc]; \\ returns an uninitialized NSArray
 
Hi,
And if i call it using alloc, then I have to manually release it, whereas using an init method, this also sends an autorelease method, so i just have to drain my pool at the end....right?
 
Generally speaking, if you do not create the object with alloc/init combo then you don't explicitly need to release it later. But if you plan on using it for a while, you should be retaining it your self (and thus releasing it when done with it).
 
In other words, no. "init" does not call autorelease on your object. You need to call either release or autorelease yourself.
 
A fun tidbit-

Objective-C really has no concept of a constructor. It follows a completely different object initializer pattern, which arguably allows for more flexibility.

I hear this mistake a lot from the C++ guys.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.