Using attributes in the IOS category

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.