The primary role of a category is to extend functionality, which means adding new methods and not encapsulating attributes.
If you want to add an attribute, you can use the associated object helper to implement
#import "Test.h" @interface Test (Other) @property (Nonatomic,strong) nsstring *mystr; @end
#import "Test+other.h"#import<objc/runtime.h>@implementationTest (Other)Static Const Char*omystr ="Omystr";-(void) Setmystr: (NSString *) mystr{objc_setassociatedobject (self, omystr, mystr, objc_association_retain_nonatomic);}-(nsstring*) mystr{returnObjc_getassociatedobject (self, omystr);;}@end
It is important to note the memory management semantics in the Setup method:
Association type |
The equivalent @property property |
Objc_association_assign |
Assign |
Objc_association_retain_nonatomic |
Nonatomic, retain |
Objc_association_copy_nonatomic |
nonatomic, copy |
Objc_association_retain |
Retain |
Objc_association_copy |
Copy |
Categories in Objective-c