Search code examples
iosobjective-cobjective-c-category

Properties in Categories


Why is it allowed to declare properties in categories when neither they nor their accessor methods are synthesized? Is there any performance overhead involved?

Is categorisation purely a compiler technique?

I'm trying to understand how categories work. This just explains what to do and what not to do. Are there any sources which go into more detail?

EDIT : I know that I can use associated references. Thats not what I'm asking for. I want to know why are the properties not synthesised? Is there a performance issue or a security issue if the compiler synthesises them? If there is I want to know what and how?


Solution

  • Why is it allowed to declare properties in categories [...] ?

    Properties have many aspects (during compile- and runtime).

    1. They always declare one or two accessor methods on the class.
    2. They can change the selector when the compiler transforms dot notation to messages.
    3. In combination with the @synthesize directive (or by default) they can make the compiler synthesize accessor methods and optionally ivars.
    4. They add introspection information to the class which is available during runtime.

    Most of these aspects are still useful when declaring properties in categories (or protocols) and synthesizing is not available.

    Is categorisation purely a compiler technique?

    No. Categories, as properties, have both compile time as well as runtime aspects.

    Categories, for example, can be loaded from dynamic libraries at a later time. So there might already be instances of a class that suddenly gets new methods added. That's one of the reasons categories cannot add ivars, because old objects would be missing these ivars and how should the runtime tell if an object has been created before or after the category has been added.