Objective-C Associative References (continued)

Source: Internet
Author: User

Objective-C Associative References (associated References)I am reading an article on KVC today, so I want to come up with a better understanding and a more practical understanding.

CAKeyframeAnimation *animation=[CAKeyframeAnimation animationWithKeyPath:@"position"];keyPosi.path=path;keyPosi.delegate=self;[label.layer addAnimation:animation forKey:@"position"];

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{}

[animation setValue:view forKey:@"xx"];
Then I modify the callback method:

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{    if (flag) {        UIView *vie=[anim valueForKey:@"xx"];        [vie removeFromSuperview];    }}
Is this correct?

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0xf65f090> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key xx.'

Invoked by setValue:forKey: when it finds no property - ()setValue:()value forUndefinedKey:(NSString *DiscussionSubclasses can   method to handle the request  some other way. The  implementation raises an NSUndefinedKeyException.

And

#import <objc/runtime.h>@interface NSObject (KVC)- (id)valueForUndefinedKey:(NSString *)key;- (void)setValue:(id)value forUndefinedKey:(NSString *)key;@end@implementation NSObject(KVC)- (id)valueForUndefinedKey:(NSString *)key{    return objc_getAssociatedObject(self, key);}- (void)setValue:(id)value forUndefinedKey:(NSString *)key{    if ([value isKindOfClass:[NSString class]]) {        objc_setAssociatedObject(self, key, value, OBJC_ASSOCIATION_COPY_NONATOMIC);    }else{        objc_setAssociatedObject(self, key, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);    }}@end

This achieves the goal.


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.