Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No warning for id?

I have just spotted something that I am a little puzzled about, I wonder if someone would be so kind as to clarify it for me.

NSArray *nextArray = [NSArray arrayWithObjects:@"ONE", @"TWO", @"THREE", nil];
for(id eachObject in nextArray) {
    NSLog(@"COUNT: %d", [eachObject length]);
}

Why does the above not complain/warn about the fact that I am asking for the length of an id?

like image 991
fuzzygoat Avatar asked Dec 04 '22 02:12

fuzzygoat


2 Answers

In Objective-C id is the general type for any kind of object regardless of class and can be used for instances of a class and for class objects themselves. The id type is completely nonrestrictive it has no information about an object, except that it is an object. So there's no way for the compiler to know whether or not that object can respond to a method because it doesn't know what kind of object it is. By using it in your code you're basically saying 'to whatever this is pointing to, perform this operation'.

like image 136
Iñigo Beitia Avatar answered Dec 15 '22 07:12

Iñigo Beitia


You use id when you specifically do not want compiler type checking. You can send any message to an id type without a warning, and you can assign an id to any other type without a type cast.

This allows you to fetch an object from an array without using a cast. E.g., you're free to assume that the array contains NSStrings:

NSString* someString = [myArray objectAtIndex:1];

It also allows you to send a message to an object without a cast or a warning. In fact, the message you wish to send may not be part of any formal class or protocol:

id someObject = [myArray objectAtIndex:1];
if ([someObject respondsToSelector:@selector(setName:)])
{
    [someObject setName:@"Foo"];
}
like image 32
Darren Avatar answered Dec 15 '22 09:12

Darren