-1

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
sanjayzed
  • 57
  • 9

1 Answers1

1

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:

//FooClass.h
@interface FooClass : NSObject

@property (nonatomic, strong) NSString *bar1;

@end

That defines a class with 1 property bar1 and backed by an instance variable _bar1.

An external category of FooClass could not add extra instance variables to FooClass.

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:

//  FooClass.m
@interface FooClass()
@property (nonatomic, strong) NSString*bar2;
@end

@implementation FooClass

@end

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

Community
  • 1
  • 1
Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • how to demonstrate "Adding stored properties to an object changes the object's memory allocation" . can you pls give me one example. Thanks for your reply – sanjayzed Sep 10 '16 at 19:08
  • See the edit to my answer. – Duncan C Sep 10 '16 at 19:17
  • Please get the terminology correct. Objective-C categories allow you to add properties. They don't allow you to add instance variables. – rmaddy Sep 10 '16 at 20:53
  • rmaddy, good point. I'll edit my answer. – Duncan C Sep 10 '16 at 21:03
  • Duncan . Thank you for brief explanation. I understood the concept of categories and extensions. I still dont understand how upon adding ivar to an object changes its memory location and requires objects to be recompiled. – sanjayzed Sep 11 '16 at 07:52
  • @sanjayzed, see the linked duplicate question for a more thorough discussion. – Duncan C Sep 11 '16 at 11:40