我在NSObject和CALayer中测试@dynamic,当DynamicTest类继承NSObject时,运行
test.title = @"title";
它崩溃是因为 DynamicTest 类中没有 setter/getter 方法。
@interface DynamicTest : NSObject
@property NSString *title;
@end
@implementation DynamicTest
@dynamic title;
@end
DynamicTest *test = [[DynamicTest alloc] init];
test.title = @"title";//crashed
但是当 DynamicTest 类继承 CALayer 时,它起作用了!
@interface DynamicTest : CALayer
@property NSString *title;
@end
@implementation DynamicTest
@dynamic title;
@end
DynamicTest *test = [[DynamicTest alloc] init];
test.title = @"title";//it works!
我知道CALayer为此做了一些事情,我想知道细节,期待你的帮助,谢谢!
最佳答案
阅读Core Animation Programming Guide: Key-Value Coding Extensions :
The
CAAnimation
andCALayer
classes are key-value coding compliant container classes, which means that you can set values for arbitrary keys. Even if the keysomeKey
is not a declared property of theCALayer
class, you can still set a value for it as follows:[theLayer setValue:[NSNumber numberWithInteger:50] forKey:@"someKey"];
虽然没有明确说明,但这种支持扩展到提供动态访问器。
关于ios - 为什么CALayer的动态@property可以调用setter方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53926901/