Melvin Lai
Melvin Lai

Reputation: 901

Explanation of Class Methods and Instance Method

Until now, I would like to know the difference between these 2. I always been using instance methods but have no idea the meaning behind it. Can anyone explain in the simplest way? Thanks.

Upvotes: 0

Views: 334

Answers (2)

jtbandes
jtbandes

Reputation: 118681

Class methods are called on the classes themselves, like this:

[NSDate date];
// declared as: + (NSDate *)date;

Instance methods are called on actual objects:

NSDate *date = ...;
[date timeIntervalSinceNow];
// declared as: - (NSTimeInterval)timeIntervalSinceNow;

Read the The Objective-C Programming Language guide for more information.

Upvotes: 1

rckoenes
rckoenes

Reputation: 69469

Well class methods can be used without making an instance of a class. Since you don't have an instance of this class you can't use any class instance variables.

ex:

@implementation MyStringHelper


@synthesize lastChecked;

+ (BOOL) checkIfEmptyString:(NSString *)checkString {
  return ([checkString length] == 0);
}
@end

Thus you can call this like:

if ( [MyStringHelper checkIfEmptyString:@"NotEmprty"] ) {
// do something
}

But you can't use the properties latChecked because this will need an instance of the MyStringHelper class.

Upvotes: 0

Related Questions