Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

chrono1081

macrumors G3
Original poster
Jan 26, 2008
8,453
4,154
Isla Nublar
Hi guys,

I'm catching up with modern Objective-C and found this document:

Adopting Modern Objective-C

and it is talking about using instance type but I'm a bit confused.

On one line it says:
Use the instancetype keyword as the return type of methods that return an instance of the class they are called on (or a subclass of that class). These methods include alloc, init, and class factory methods.

Then in another line it says:
In your code, replace occurrences of id as a return value with instancetype where appropriate. This is typically the case for init methods and class factory methods. Even though the compiler automatically converts methods that begin with “alloc,” “init,” or “new” and have a return type of id to return instancetype, it doesn’t convert other methods. Objective-C convention is to write instancetype explicitly for all methods.

So my question is is id never used anymore? Can anyone give a simple explanation of where to use it and where not to use it?
 

chown33

Moderator
Staff member
Aug 9, 2009
10,740
8,416
A sea of green
Consider NSDictionary. It can hold objects of any type. Therefore, the return type for objectForKey: should be id, not instancetype.

The same principle applies to the key object; it can be any type, so the type of keys and objects in setObject:forKey: would also be id.

The principle also applies to other classes, such as everything in the Collections library. NSDictionary was just the first collection I thought of.

You can browse the class reference doc for NSDictionary and NSMutableDictionary and see where it uses instancetype vs. where it uses id.
https://developer.apple.com/library...ableDictionary_Class/Reference/Reference.html
 

PhoneyDeveloper

macrumors 68040
Sep 2, 2008
3,114
93
objectForKey can return an object of any type.

init can only return an object of the type of the class its called on or a subclass of that type.
 

chrono1081

macrumors G3
Original poster
Jan 26, 2008
8,453
4,154
Isla Nublar
Thanks guys.

I'm still pretty confused but I'll work through it. A good amount has changed since I touched Objective-C last.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.