zoukankan      html  css  js  c++  java
  • synthesize & property

    Using a declared property for the interface but implementing the property manually by writing the accessor implementations yourself is perfectly fine. It's important to the users of your class that your implementation match the semantics of the declared property, of course. If you manually implement the accessors, then you are responsible for implementing whatever details (such as an instance variable) that the accessor implemenations need.

    Alternatively, another way the compiler can help is to synthesize the implementation of the properties. There are two modes for property synthesis, automatic and explicit. If you neither manually implement the accessor methods nor "@synthesize" the property, then the compiler will automatically synthesize it. It will generate an instance variable for the property's storage, using the naming convention with the leading underscore, or use an instance variable of that name if you explicitly declared one. It will also generate the accessor methods with the proper semantics to match the @property declaration.

    If you explicitly synthesize a property with the @synthesize keyword, then the compiler will do something similar but slightly different. If your @synthesize statement doesn't explicitly associate an instance variable name with the property, then it will use a variable name without a leading underscore. So:

    @synthesize firstName;

    generates an instance variable named "firstName", not "_firstName", and uses that in the accessor implemenations it provides. To use the conventional name, you'd need to be explicit:

    @synthesize firstName=_firstName;

    The second difference is that explicit synthesis can be combine with manual implementation. The compiler will provide the pieces (instance variable, getter, setter) that you do not.

    https://developer.apple.com/forums/thread/69075

    @interface ViewController ()

    {

        NSString *string;

    }

    @property(nonatomic, strong) NSArray *array;

    @property(nonatomic, strong) NSDictionary *dic;

    @property(nonatomic, strong) NSString *string;

    /*

     //@synthesize string;

     Autosynthesized property 'string' will use synthesized instance variable '_string', not existing instance variable 'string'

     */

    @end

    @implementation ViewController

    @synthesize dic;

    //@synthesize string;

    - (void)viewDidLoad {

        [super viewDidLoad];

        // Do any additional setup after loading the view.

        _array = @[];

        dic = @{};

    }

  • 相关阅读:
    iOS 最新版 CocoaPods 的安装流程
    AFNetworking 3.0.4 的使用
    NSPredicate谓词
    PHP基本类型操作
    MJExtension使用指导(转)
    字典转模型KVC和runtime二者实现与区别
    iOS之KVC字典转模型的底层实现
    runtime 总结(原创)
    Objective-C Runtime能做什么?
    Runtime那些事儿(消息机制)
  • 原文地址:https://www.cnblogs.com/feng9exe/p/13431926.html
Copyright © 2011-2022 走看看