0

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:

http://i32.tinypic.com/2we992r.png

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.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
JonB
  • 4,422
  • 2
  • 27
  • 25

1 Answers1

7

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.

teabot
  • 15,358
  • 11
  • 64
  • 79
  • 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? – JonB Jul 10 '09 at 09:13
  • 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. – teabot Jul 10 '09 at 09:16
  • 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. – RCIX Jul 10 '09 at 09:16
  • 1
    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:" – cobbal Jul 10 '09 at 09:18
  • 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 Jul 10 '09 at 09:18
  • 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 Jul 10 '09 at 09:20
  • 1
    @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. – Daniel Rinser Jul 10 '09 at 13:47
  • @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. – Quinn Taylor Jul 10 '09 at 14:51