What is the underlying mechanism for ivar synthesis in the modern Objective C runtime

孤者浪人 提交于 2019-11-28 18:20:16

I went and looked at the documentation again just now, and I think you're misreading it. Synthesized ivars are created at compile time, not at run time.

According to the Objective-C 2.0 documentation:

There are differences in the behavior that depend on the runtime (see also “Runtime Differences”):

For the legacy runtimes, instance variables must already be declared in the @interface block. If an instance variable of the same name and compatible type as the property exists, it is used—otherwise, you get a compiler error.

For the modern runtimes, instance variables are synthesized as needed. If an instance variable of the same name already exists, it is used.

So all you need to do is declare the instance variable you need, and the same code will work on both runtimes...

What you are looking for is @synthesized name, like:

@synthesize name = _name;

...

- (NSString *) name {
    if (!name) {
        _name = @"Louis";
    }

    return _name;
}

You add properties at run-time with the NSKeyValueCoding Protocol.

[myObject setValue:@"whatever" forKey:@"foo"];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!