Hi,
I'm just starting to teach myself objective-c and attempting to learn the cocoa touch frameworks, as like many people recently I have developed an interested in a certain little multi-touch device.
Anyway, I'm following the Stanford tutorials and I have couple of Objective-C books that im starting to make my way through. While completing one of the assignments produced by stanford, I ended up looking at the array documentation and noticed this:
Some methods have + 's and some have - 's. Whats the difference? I swear i've read what it is somewhere else before but can't for the life of me remember.
-
A minus signifies an object instance method, a plus signifies a class method - known in other languages as a 'static method'.
More info on method types can be found in this wikipedia article.
JonB : Ok, so if I understand this correctly, I would create a new instance of the array object and use the minus sign? When would I find myself using the plus sign with an array then. Surely I always have to create an instance of an array to use one?teabot : Using NSArray as an example, you might call the class method [NSArray arrayWithObject:] to create an instance of NSArray containing the object you pass in.RCIX : As i understand it, those are for the function definitions. if one is defined with a plus then you call it through the class. Otherwise, you call it through an instance.cobbal : an example may be the best way to clarify this: [NSMutableArray arrayWithCapacity:10] and [[[NSMutableArray alloc] initWithCapacity:10] autorelease] are equivalent, one is "+ arrayWithCapacity:" the other is "-initWithCapacity:"JonB : Just to clarify, I understand what a static method is. I just can't see why there would need to be one for an Array, when surely every-time you have to create an instance of an Array to use one?JonB : Ah, so it allows you to create an array without having to make the instance first. You still get given an array object at the end of it. Makes sense.JonB : Thanks for your help all.Daniel Rinser : @JonB: Exactly, it's actually a factory method. Note however that those factory methods return autoreleased instances, whereas instances created viaalloc/init have to be released manually. This is a common (and hard to debug) memory management mistake.Quinn Taylor : @Daniel is correct that +arrayWith... methods are factory methods (in Objective-C we generally call static methods with this functionality "convenience constructors"), but of course not all static methods are or must be. For example, NSURLProtocol is an abstract class with a number of static utility methods.
0 comments:
Post a Comment