objective c - Add ivar and property to class using class extension -
i'm trying add instance variable , property existing class. want extend base class of open source library, without modifying source code (for easier code management).
the documentation says
unlike regular categories, class extension can add own properties , instance variables class. if declare property in class extension [...] compiler automatically synthesize relevant accessor methods, instance variable, inside primary class implementation.
i tried in test app. have empty class classa:
classa.h
#import <foundation/foundation.h> @interface classa : nsobject @end classa.m
#import "classa.h" @implementation classa @end
added extension:
classa+ext.h
#import "classa.h" @interface classa () @property (nonatomic) nsstring *name; // <-- new property @end
in appdelegate init classa , try set , log name.
#import "appdelegate.h" #import "classa.h" #import "classa+ext.h" @implementation appdelegate - (void)applicationdidfinishlaunching:(nsnotification *)anotification { classa *a = [[classa alloc] init]; a.name = @"test"; nslog(@"name: %@", a.name); } @end this compiles , runs, error on console:
2013-05-10 00:58:08.598 test[53161:303] -[classa setname:]: unrecognized selector sent instance 0x108a1a630 2013-05-10 00:58:08.600 test[53161:303] -[classa setname:]: unrecognized selector sent instance 0x108a1a630 the name not logged. , if set breakpoint , inspect classa instance, doesn't have name ivar. doing wrong? isn't possible do?
your understanding incorrect. added property through class extension. property should able used inside class. should not used true "property" class in can change through external instantiation. think of pseudo private instance variable.
i believe want subclass class a.
another viable solution proposed was:
"you can write category wrap -[setassociatedobject:forkey:]" when using objc_setassociatedobject --> @artur
Comments
Post a Comment