Objective-C Associative References(關聯引用) 一篇文章,今天在看KVC方面的文章,所以就想到結合一起再講明白一點,更加結合實際一點
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"];
然後我就修改回調方法:
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{ if (flag) { UIView *vie=[anim valueForKey:@"xx"]; [vie removeFromSuperview]; }}
這樣正確嘛?
*** 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.
和
#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
這樣就實現了目的。