Add property to category by Ocruntime

Source: Internet
Author: User

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

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.