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.
-
possible duplicate of Objective-C: Class vs Instance Methods?csano– csano2011-08-10 07:26:26 +00:00Commented Aug 10, 2011 at 7:26
-
thanks for the link. the one I saw was the java. Although explanation could be the same. I was looking for the obj c one. Thanks!Melvin Lai– Melvin Lai2011-08-10 07:39:22 +00:00Commented Aug 10, 2011 at 7:39
Add a comment
|
2 Answers
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.
4 Comments
Melvin Lai
Thanks, but even if I just read the link j0k sent. I am still feeling confused.
jtbandes
What are you confused about? Did you read the link I put in my answer? Class/instance methods are common to many object-oriented languages, so it would be good to get a grasp on OOP in general.
Melvin Lai
Yea, I read your link. But still I do not understand still. Can I say that Class methods can only call methods within its own class? Thats what I am seeing in your code.
Melvin Lai
oh man, now i feel more confused :( i guess it would be better if i find some obj c tutorials on class and instance methods.
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.