Hi everyone! I decided to write a quick tutorial about the + and - you see in front of methods. So real quick, what are they? Well they're prefixes to define a method as either a class or an instance method. What's the difference? Well the difference is how you can call the method. Let's make a quick file called by everyone's favorite name
SomeClass.h
Code:
@interface SomeClass:NSObject
{
NSString *str;
NSInteger x;
}
/*instance methods*/
-(void)doSomething;
-(void)doSomething:(NSString *)string;
-(void)doSomething:(NSString *)string withInt:(NSInteger)integer;
/*class methods*/
+(void)doSomethingAsWell;
Now in
SomeClass.m
Code:
import "SomeClass.h"
@implementation SomeClass
-(void)doSomething
{
str = @"This is a string";
x = 15;
}
-(void)doSomething:(NSString *)string
{
str = string;
x = 15;
}
-(void)doSomething:(NSString *)string withInt:(NSInteger)integer
{
str = string;
x = integer;
}
+(void)doSomethingAsWell
{
str = @"So what if it's a string";
x = 20;
}
Now if you were to import
SomeClass, here's what you can do:
Code:
SomeClass *class = [SomeClass alloc];
[class doSomething];
[class doSomething:@"Some text"];
[class doSomething:@"Some text" withInt:20];
[SomeClass doSomethingAsWell];
So you probably notice from that in the 2, 3, and 4 lines I used the variable "class" in the beginning. This is because those methods can only be done if there is a SomeClass variable/instance/object. The 5 line did not need 'class' to work because it is a class method, all you need to do is import the class and just use the class name directly.
Instance methods are normally used when you have a object type that is the same for a bunch of things, but different values within the object. For example, if I had an Employee class with the variables 'hours' and 'wage' for each employee, I could do a
getPay instance method for each employee.
Class methods are used when objects have something in common and you don't really need to create an object for it. For example, using the Employee class again, I could make a
getOvertimePay: if all employees are paid the same for overtime.
Anyway I hope that this is helpful to you.