Reputation: 26223
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?
Upvotes: 4
Views: 110
Reputation: 27073
The NSArray
might contain different object types, for example:
NSArray *thArray = [[NSArray alloc] initWithObjects:@"Stack",@"Overflow",[NSNumber numberWithInt:10],nil];
for(id theObject in thArray) {
NSLog(@"COUNT: %lu", [theObject length]);
}
The id
can represent any object (in this case NSString
or NSNumber
),
therefor the compiler cannot know whether the primitive method length
exists.
Upvotes: 3
Reputation: 25619
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"];
}
Upvotes: 4
Reputation: 6353
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'.
Upvotes: 5
Reputation: 9600
Simply, id means all Objective-C Class. so, length method it belongs a NSString Class. Compiler no throw warning to you. id is determined dynamically at runtime, is unknown at compile time.
Upvotes: 1
Reputation: 8527
Each object in Objective-C knows what class it has and if it can handle a message. It's not the compiler who checks the class, it is the object itself at runtime.
The class of an object can be undefined at compilertime, but at runtime each object has a defined class.
Upvotes: 0
Reputation: 306
The compiler will never type check messages sent to an id. It's partly what enables Objective-C's dynamism.
If eachObject was any other type, then you would get an error if the compiler couldn't resolve the method name.
Upvotes: 4