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

前端 未结 3 1832
时光说笑
时光说笑 2020-12-13 20:35

One of the features of the modern (64 bit OS X and iPhone OS) Objective C runtime is the ability for properties to dynamically synthesize ivars without explicitly declaring

相关标签:
3条回答
  • 2020-12-13 21:14

    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...

    0 讨论(0)
  • 2020-12-13 21:14

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

    @synthesize name = _name;
    
    ...
    
    - (NSString *) name {
        if (!name) {
            _name = @"Louis";
        }
    
        return _name;
    }
    
    0 讨论(0)
  • 2020-12-13 21:18

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

    [myObject setValue:@"whatever" forKey:@"foo"];
    
    0 讨论(0)
提交回复
热议问题