iOS Extended Properties: Category You can extend the methods of a class, but you cannot expand the properties of a class. If you want to extend the properties of the class, you can use associative, which is relatively small compared to the category, and he also uses the runtime programming, must use <OBJ/RUNTIME.H>, using Objc_getassociatedobject , Objc_setassociatedobject and Objc_removeassociatedobjects. The lives of these methods are as follows:
The sample code is as follows:
1. Create a person class first
#import <Foundation/Foundation.h>@interface Person : NSObject@property (nonatomic, copy) NSString *name;@end#import "Person.h"@implementation Person@end
2. Create a new category and use associative to add attributes
#import"Person.h"@interfacePerson (Addproty)@property (Nonatomic,CopyNSString *addr; @end #import #import <objc/runtime.h> @implementation person ( addproty) static char straddrkey = ' a ';-( Span class= "hljs-built_in" >nsstring *) addr{return objc_getassociatedobject (self, &straddrkey);} -(void) setaddr: (nsstring *) addr{Objc_setassociatedobject (self, &straddrkey, addr, objc_association_copy_nonatomic);} @end
Using attributes in the IOS category