sanjayzed
sanjayzed

Reputation: 57

Objective-C categories doesn't allow to add instance variables

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.

Upvotes: -1

Views: 1243

Answers (1)

Duncan C
Duncan C

Reputation: 131398

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

Upvotes: 1

Related Questions