0

In code like

- (void)driveFromOrigin:(id)theOrigin toDestination:(id)theDestination;
- (id)initWithModel:(NSString *)aModel;

does id allow me to specify a type?

Pétur Ingi Egilsson
  • 4,368
  • 5
  • 44
  • 72
Pépito
  • 57
  • 4
  • 11
  • 1
    See http://stackoverflow.com/questions/7987060/what-is-the-meaning-of-id – rmaddy Mar 23 '14 at 17:10
  • Semantically they are very different. One uses id to opt out of type checks, one uses auto to have types inferred for you. – CodaFi Mar 23 '14 at 21:29

3 Answers3

3

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".

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • it is absolutely fine for `init…` signature to return `id`. due to naming conventions the compiler is aware that `init` must return an object of the same class or a subclass. `intancetype` is a good choice for convenient or factory methods, though. – vikingosegundo Mar 23 '14 at 17:49
  • `instancetype` is redundant for several methods including `-init...`; this is known as ["inferred related result type"](http://clang.llvm.org/docs/LanguageExtensions.html#related-result-types). – jscs Mar 23 '14 at 18:33
1

Yes, in xcode8, you can use __auto_type

user49354
  • 199
  • 1
  • 8
0

not exactly. id means objective-c object type. compiler wouldn't know its type during compilatrion. auto instructs the compiler to inference variable type.

Michał Banasiak
  • 950
  • 6
  • 13