简体   繁体   中英

Is an ivar added by objc_setAssociatedObject the same as common ivar in Class declaration?

@interface XXX : NSObject {
    NSString    *any;
}

compare with:

objc_setAssociatedObject(self, "any", @"xxx", OBJC_ASSOCIATION_COPY);

Are they all put into location below?

struct objc_ivar_list *ivars 

No, these are different technologies.

An ivar is defined at compile time and when an instance is allocated, the memory space for it is allocated. (Please, keep in mind that NSString* is the type of the ivar, so memory space for a reference is allocated, not for the instance of NSString itself.)

An association is stored in a dictionary style memory space related to an instance.

However, if you want to set a value, whose key you know at runtime only, use key-value coding:

[self setValue:@"xxx" forKey:@"any"];

This will execute the setter -setAny: , what likely sets the ivar.

Declaring a declared property ( @property ) is something completely different. A property declaration solely declares methods. If it is done in the class or a class continuation, an ivar is synthesized under some circumstances. In a category it is never synthesized, since synthesization if impossible in a category.

It's my fault that I didn't express clearly, I want to know if there is a new ivar put into objc_ivar_list when I use association. Now I understand.Thx.And can you tell me is there any differences when I declare a property in a Class and its catagory?And why design like this – Max Wang Dec 17 at 7:51

Sorry, I have no reputation enough to add a comment to answer this question. Let me tell you the differences between property in Class and in category. If a property is declared in class, the compiler will automatically generate setter and getter method for this property, as you know. However, in category, even though you are allowed to declare property for that class, the compile would never generate setter and getter method for you . If you try to visit property declared in category, Xcode will throw *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[XXXX setSomeProperty:]: unrecognized selector sent to instance 0x798342c0' because there is no existing method. This is why we need objc_setAssociatedObject and objc_getAssociatedObject to generate setter and getter manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM