Sunday, October 16, 2011

Instance methods and class methods

I have a somewhat decent grasp of common OOP terms like class, method, inheritance, polymorphism, etc. Something that I keep seeing in my casual reading about Objective-C is that some methods in class definitions have + preceding them, and others -.

The + means the method is a class method, and the - means it's an instance method. An example in the book I'm reading today (Objective-C Programming: The Big Nerd Ranch Guide) illustrated one difference between the two.

The NSDate class has a method called date which returns a pointer to an instance of the NSDate class.

NSDate *sometime = [NSDate date];

date is a class method.

There is another method called timeIntervalSince1970 which returns a double (seconds since 1970). This is an instance variable, so you call it on the instance.

double timepassed = [sometime timeIntervalSince1970];

It's not legit to say:

double timepassed = [NSDate timeIntervalSince1970];

and you'll get warned that no such class method exists.

So there's OOP with Objective-C lesson one. There are class methods and instance methods. I tried doing a few different things, like:

NSDate *now = [NSDate];

but I got an error "Expected identifier". Is an identifier a class method that has to be run? Is this the concept as a constructor in C++? I peeked into NSDate.h and found a few other class methods alongside date. I found an instance method called init and thought I should try it too

NSDate *now = [NSDate init];

and this didn't give me an error. So that's confusing - both init and timeIntervalSince1970 are instance methods but the former works and the latter fails. Going back to NSdate.h I found that timeIntervalSince1970 isn't quite in the same place as init is, so maybe it has different rules. Further confusing the matter is that init is of type id which is a generic pointer to an Obj-C object, and timeIntervalSince1970 is a double.

Well shoot. I mean this post to be about how I learned something and now I'm just more confused.

No comments:

Post a Comment