I would like to know why Objective-C design pattern of categories has designed in a way that we cannot able to add instance variables.
And also I came to know that using Objective-C associated objects we can able to do. But I am more interested what is the main reason behind it.
Answer edited to talk about instance variables rather than properties.
Adding instance variables to an object changes the object's memory allocation, and requires that the object be recompiled. Categories add new methods to existing objects without requiring a recompile, and therefore can't add instance variables.
As you say, you can add properties where the data is saved & loaded using associative storage.
EDIT:
If you have a class FooClass with a header like this:
That defines a class with 1 property
bar1and backed by an instance variable_bar1.An external category of
FooClasscould not add extra instance variables toFooClass.However, you can create a "private category" in the .m file for FooClass that CAN define additional properties (with backing instance variables) to the class. It works because those additional instance variables are known at compile-time, and can be "baked into" the class. Here's an example:
Note the extra @interface declaration, with an additional property. Since it's in the same .m file as the implementation, it isn't exposed to other files, but it is known at compile-time, so the compiler can add the needed instance variable(s).