An analysis of IOS runtime (runtime)

Source: Internet
Author: User

This blog, directly from the classification. All know that the classification in OC can not directly add attributes, meaning indirectly can add attributes. So how do you add it? It's going to use the runtime mechanism.

  

One, one of the usage of the Golden Code at runtime

Now, add a category to the Hgperson class: Hgperson+hg.h, give a property as follows:

@property (nonatomic, copy) nsstring* name;

Looks like, after this writing, is able to call, but the operation of the error.

-[hgperson SetName:]: Unrecognized selector sent to instance 0x7f90b2e13620

2015-10-02 20:41:28.803 runtime[3357:285701] * * * terminating app due to uncaught exception ' Nsinvalidargumentexception ', Reason: '-[hgperson setName:]: Unrecognized selector sent to instance 0x7f90b2e13620 '

It means that this method has not been found:-[hgperson setName:] .... Oh, I see. There is no implementation in the classification, so the error.

Now we start to use the OC Runtime mechanism to dynamically add member variables to a class. Code is as follows:

#import "Hgperson+hg.h"

#import <objc/message.h>

@implementation Hgperson (HG)

/**

Dynamically add a member variable to this class

*/

This key is used for reference < I'm not too clear, not a member variable

static double Namekey;

-(void) SetName: (NSString *) name {

Objc_setassociatedobject (self, &namekey, name, objc_association_copy_nonatomic);

}

-(NSString *) name {

Return Objc_getassociatedobject (self, &namekey);

}

@end

Second, the use of the Golden Code in the operation of the second

Record the number of member variables in the Hgperson class

Nsinteger count;

Get a list of all member variables in the Hgperson class

ivar* Ivars = class_copyivarlist (Objc_getclass ("Hgperson"), &count);

Traversing member variables in the Hgperson class

for (Nsinteger i=0; i<count; i++) {

Ivar IAVR = ivars[i];

Const char* name = Ivar_getname (IAVR);

Const char* type = ivar_gettypeencoding (IAVR);

}

An analysis of IOS runtime (runtime)

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.