【问题标题】:Why CALayer's dynamic @property can invoke setter method?为什么CALayer的动态@property可以调用setter方法?
【发布时间】:2018-12-26 02:31:00
【问题描述】:

我在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为此做了一些事情,我想知道细节,期待您的帮助,谢谢!

【问题讨论】:

    标签: ios objective-c calayer


    【解决方案1】:

    阅读Core Animation Programming Guide: Key-Value Coding Extensions

    CAAnimationCALayer 类是符合键值编码的容器类,这意味着您可以为任意键设置值。即使键 someKey 不是 CALayer 类的声明属性,您仍然可以为它设置一个值,如下所示:

    [theLayer setValue:[NSNumber numberWithInteger:50] forKey:@"someKey"];
    

    虽然没有明确说明,但这种支持扩展到提供动态访问器。

    【讨论】:

    • 你知道为什么动画自定义图层属性应该使属性为@dynamic吗?
    猜你喜欢
    • 2015-11-13
    • 2015-03-21
    • 2020-12-09
    • 2013-08-20
    • 1970-01-01
    • 2018-06-05
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多