Reputation: 57
In code like
- (void)driveFromOrigin:(id)theOrigin toDestination:(id)theDestination;
- (id)initWithModel:(NSString *)aModel;
does id
allow me to specify a type?
Upvotes: 0
Views: 1433
Reputation: 52538
id is similar to "void*". It means "pointer to any kind of Objective-C instance". So unlike a void*, it is under ARC control. It can be assigned to any variable of type "pointer to Objective-C object" and vice versa.
Using variables of type "id" has the disadvantage that the compiler has no idea what kind of object you have, so it will allow you to send messages to it, even if it doesn't understand them.
NSString* aString = @"Hello";
NSUInteger count = aString.count; // Doesn't compile because the compiler knows it's wrong
id bString = aString; // It's a string, but the compiler doesn't know.
count = bString.count; // Compiles but throws exception at runtime.
"auto" in C++ is different. It determines the correct type from the argument on the right hand side. So the variable is fully declared except that the compiler provided the type and not you.
PS. "init" methods should return "instancetype" and not id. "instancetype" is kind of, roughly, similar to "auto".
Upvotes: 3
Reputation: 960
not exactly. id means objective-c object type. compiler wouldn't know its type during compilatrion. auto instructs the compiler to inference variable type.
Upvotes: 0