In general, the category can add methods to existing classes or declare property for existing classes, but cannot automatically generate implementation code for the corresponding property. In other words, even if you add a property to a class by category, you cannot access the property in the form of "Self.name". But! With the help of runtime, this is not a problem. For example, I intend to add a property (name) to the Nsarray class, which can be declared as follows:
@interface Nsarray (swizzling) @property (Strong, nonatomic) NSString *name; @end
In NSARRAY+SWIZZLING.M, you can write as follows:
@implementation Nsarray (swizzling) @dynamic name;//Use the dynamic statement, or you can not write this sentence ... @end
So far, if you call name directly using the following method, you will get an error:
Nsarray *arr=[nsarray arraywithobjects:@ "AA", @ "BB", @ "CC", nil]; [Email protected] "Layne";
"-[__nsarrayi SetName:]: Unrecognized selector sent to instance 0x7fa3c9524700" displays an access method that the Name property does not respond to. Therefore, in order for the Name property to be accessed like a normal property, a custom accessor is required. The code is as follows:
@implementation Nsarray (swizzling)-(void) SetName: (NSString *) name{objc_setassociatedobject (self, @selector (name), name,objc_association_retain_nonatomic);} -(NSString *) name{nsstring *n = Objc_getassociatedobject (self, @selector (name)); return n;} @end
This way, you can access the property by Arr.name.
This article is from the "Layne Learning Corner" blog, please be sure to keep this source http://laynestone.blog.51cto.com/9459455/1701247
Add property to category by Ocruntime