jer_francis
jer_francis

Reputation: 153

Objective-C id & NSObject

I understand that id is for any Object type even objects that do not inherit NSObject such as things from Cocoa. I have been told to almost always use id but what if I were making an API and had a method that I wanted to make it clear that it should only take a certain type of object such an object called Animal, would I still use

(id) animal

or would I do

(Animal) animal

Thanks so much!

Upvotes: 3

Views: 276

Answers (2)

Caleb
Caleb

Reputation: 124997

id is a generic pointer to an object -- it's like void *, except that the pointer must point to an Objective-C object. So yes, you could use id in most situations where a more specific object pointer type would work, but it's usually better to use the more specific type:

- (id)animal;  // OK if 'animal' could be any type of object
- (Animal*)animal; // much better if you know that 'animal' points to an object of type 'Animal'

You'll find plenty of examples if you look at any Cocoa or Cocoa Touch class. Let's look at a little bit of UIView:

- (BOOL)isDescendantOfView:(UIView *)view;  // returns YES for self.
- (UIView *)viewWithTag:(NSInteger)tag;     // recursive search. includes self

As you can see, the first method takes a UIView* as a parameter. If you try to pass something other than a pointer to an instance of UIView, the compiler will complain.

The second method returns a UIView*, and you can use the result directly as the receiver of other messages that UIView understands:

[[topView viewWithTag:someTag] removeFromSuperview];

Being specific about the types of parameters and return values lets the compiler help you make sure that you're sending appropriate messages to your objects and getting appropriate values back.

Upvotes: 6

Andrey Chernukha
Andrey Chernukha

Reputation: 21808

You can use any type starting from Animal and then up through inheritance chain to NSObject and id. Any would be valid. But in most cases you need to use just Animal because this is the very type you need to work with

Upvotes: 2

Related Questions