Scott Davies
Scott Davies

Reputation: 3755

Is self ever used in returning a reference to a class in Objective-C?

I am working through a book on Cocoa and Objective-C. One example has stumped me:

- (id) currentObject {
   return [Photo photo];
}

- (void) checkObjectType {
    id object = [self currentObject];
    ...
}

In this case, checkObjectType calls currentObject. currentObject then returns an instance of Photo, however, it's creating a new instance of Photo and returning this reference, is it not ? Isn't it not return a reference to itself ? I was expecting something like:

return self;

Thanks,

Scott

Upvotes: 1

Views: 101

Answers (3)

James Huddleston
James Huddleston

Reputation: 8448

You must be referring to Scott Stevenson's book. The example given is just trying to show how to use the isMemberOfClass: method. I wouldn't read any more into it than that.

Your confusion is understandable. As you've already figured out, the currentObject: method returns a newly-created autoreleased object, not the object itself as its name would imply. It's a poorly named method. Maybe it's just a sneaky way of reminding the reader to name methods appropriately. :)

Upvotes: 2

dredful
dredful

Reputation: 4388

I am probably going to jack this up but here goes...

Your code snippet is within a class. That class has a method called currentObject that returns a Photo object.

id object = [self currentObject];

This is asking the current class self to call the method currentObject which just so happens to be a Photo object. Take that photo object and assign it to object

If the section of the book is discussing the type id then this seems to be a static example for method that is designed to show how an (id) method like currentObject could return any kind of object.

Maybe a better example would have been:

- (id) currentObject:(NSString *)someKey {
   return [someDictionary objectForKey:someKey];
}

- (void) checkObjectType {
    id object = [self currentObject:@"photo"];
    ...
}

Where someDictionary contained a variety of objects like a NSString, Photo and NSURL. The currentObject could handle them all.

Upvotes: 1

David Gelhar
David Gelhar

Reputation: 27900

Yes, currentObject is returning the result of [Photo photo]. Assuming that normal Cocoa naming conventions are being followed, Photo is a class (because it begins with a capital letter), so +photo is a class method that (presumably) returns an instance of the Photo class. Because the method name does not contain alloc or copy, we can further deduce that it returns an autoreleased object.

The "currentObject" method name is certainly confusing in this instance, but doing this:

- (id) currentObject {
   return self;
}

would be completely pointless: [self currentObject] would just be the same as saying self

Upvotes: 0

Related Questions