+ and - in method definitions


#1

In the description of the Challenge in this chapter, we have the following:

  • (NSHost *)currentHost

and

  • (NSString *)localizedName.

What does the + and - mean? Or, if there’s an explanation in the documentation of Xcode, please could you point it out to me?

Many thanks

David


#2
  • means that the method is only defined at the class level. This is commonly done to create new instances of objects, either via alloc to create enough memory for the instance, or via a more complex method that will create a fully fleshed-out object. currentHost is such a method.

Whenever such a method is called, it must be passed as a message to a class, not to an instance.

  • means the method only exists for individual instances of a class. So, once you’ve created an instance of NSHost via [NSHost currentHost], you can send a localizedName message to that instance.

The most common illustration of this dichotomy is the alloc/init construct. alloc is send to the class, while init is sent to the instance of the class that alloc created.


#3

That’s really helpful - thanks!

regards

David


#4

Often the class methods are shortcuts to get an object up and running. These are often called factory methods.

So rather than something like:

You can just say:

It’s a common practice with things like NSArray and what not.

If you are just looking to get back a new object without any values in it you can substitute the ‘new’ message for the alloc init dance.

Reading the class docs will help you find these tricks.


#5

That’s interesting – thanks for the information!

Regards

David


#6

I, too, found this explanation very helpful – also the “factory” methods. Thanks for sharing!

Yvonne