Categories in Objective-c

Source: Internet
Author: User

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

Related Article

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.