Plus vs Minus In Objective-C

plus-minus-balance 3d MännchenWhenever you are working with an iOS app, you would have seen those functions and how they have a plus or a minus sign at the beginning. Ever wondered what they are? Objective-C requires that the interface and implementation of a class be in separate code blocks. That’s the reason you will see a .h and a .m file as a pair. Interface is the same as class definition in other languages. By convention, we place the interface in a header file and the implementation in a code file. In the header file, we declare functions with these ‘+’ and ‘-‘ signs. Do they make any real difference or do we have them just as part of the Objective-C language protocol? Well, they exist for a reason and there is a real difference between the signs.  

For example, most of the times, the function starts with a minus sign like this:

- (void) myFunction;

But sometimes, it will be:

+ (void) myFunction;

In a nutshell, ‘-‘ functions are instance functions and ‘+’ functions are class (static) functions. So what does that exactly mean? Let’s say you have a class called Music, and we have the following functions:

- (void) functionMinus;
+ (void) functionPlus;

You would invoke these functions with the following:

Music *myMusic = [[Music alloc] init];
[myMusic functionMinus];
[Music functionPlus];

This should explain clearly when we should use ‘-‘ and when we should use ‘+’. This is more of a syntactical description of the class vs instance concept. You should use ‘-‘ when it’s an instance of a class, like myMusic in our case. This means that the function is defined only for that instance. On the other hand, ‘+’ is used when it’s a class, like Music in our case. This means that the function is defined for the class and all of its instances. In Objective-C, you can actually invoke a class function on an instance, but the effect is no different than invoking it on the class itself (it essentially compiles to the same thing).

So technically, you can do:

[myMusic functionPlus]

Generally speaking, you shouldn’t do this as it is misleading. I am pointing it out because it is not technically wrong, it’s just bad practice!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s