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?
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'.
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"];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With