user4234
user4234

Reputation: 1527

Why we cannot add iVar in Categories?

I would like to first note that actually we "can"

Just use associated objects:

@implementation UIButton (BGButtonWithImages)

static char UIB_ImageOfButton;

-(void)setImageObject:(Image *)imageObject
{
    objc_setAssociatedObject(self, &UIB_ImageOfButton, imageObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(Image*)imageObject
{
    return (Image*)objc_getAssociatedObject(self, &UIB_ImageOfButton);
}    
@end

But that leads to another issue. Why is it that something that can be done easily with Associated Objects cannot be done regularly? Why does Apple not implement properties in categories like this?

Upvotes: 2

Views: 878

Answers (1)

user23743
user23743

Reputation:

The synthesized property accessors use instance variables. You're not allowed to add instance variables via categories because there would be no guarantee of uniqueness - the same instance variables might be added by another category.

As you notice, the inside-out object pattern lets you define accessors in categories, as long as your key for the associated object table is unique. It's fine to carry on using that. If you want first-party compiler support for generating those accessors you'd have to ask Apple.

Upvotes: 4

Related Questions