Question about instancetype...

Discussion in 'iOS Programming' started by chrono1081, May 28, 2014.

  1. chrono1081 macrumors 604


    Jan 26, 2008
    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:
    Then in another line it says:
    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?
  2. chown33 macrumors 604

    Aug 9, 2009
    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.
  3. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    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.
  4. chrono1081 thread starter macrumors 604


    Jan 26, 2008
    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.

Share This Page