When should I use @synthesize explicitly?

后端 未结 7 1553

As far as I know, since XCode 4.4 the @synthesize will auto-generate the property accessors. But just now I have read a sample of code about NSUndoManage

相关标签:
7条回答
  • 2020-11-29 15:36

    When should I add @synthesize explicitly to my code?

    Generally, if it's required: You will probably never hit a case where it's needed.

    There's one case you might find it useful, though.

    Say you're writing both a custom getter and setter, but want an instance variable to back it. (For an atomic property, this is as simple as wanting a custom setter: the compiler will write a getter if you specify a setter for a monatomic property, but not an atomic property.)

    Consider this:

    @interface MyObject:NSObject
    @property (copy) NSString *title;
    @end
    
    @implementation MyObject
    
    - (NSString *)title {
        return _title;
    }
    - (void)setTitle:(NSString *)title {
        _title = [title copy];
    }
    
    @end
    

    This will not work, because _title doesn't exist. You've specified both a getter or setter, so Xcode (correctly) doesn't create a backing instance variable for it.

    enter image description here

    You have two choices for making it exist. You can either change the @implementation to this:

    @implementation MyObject {
        NSString *_title;
    }
    
    - (NSString *)title {
        return _title;
    }
    - (void)setTitle:(NSString *)title {
        _title = [title copy];
    }
    
    @end
    

    Or change it to this:

    @implementation MyObject
    
    @synthesize title = _title;
    
    - (NSString *)title {
        return _title;
    }
    - (void)setTitle:(NSString *)title {
        _title = [title copy];
    }
    
    @end
    

    In other words, although synthesize is for practical purposes never necessary*, it can be used to define property-backing instance variables when you're providing a getter/setter. You can decide which form here you want to use.

    In the past, I've favoured specifying the instance variable in the @implementation {}, but I now think the @synthesize route is a better choice as it removes the redundant type and explicitly ties the backing variable to the property:

    1. Change the property's type, and the instance variable's type changes.
    2. Change its storage qualifier (for instance, make it weak instead of strong or strong instead of weak) and the storage qualifier changes.
    3. Remove or rename the property, and the @synthesize will generate a compiler error. You won't end up with stray instance variables.

    *-I know one case where it was necessary, relating to splitting functionality across categories in multiple files. And I wouldn't be surprised if Apple fixes this, or even already has.

    0 讨论(0)
提交回复
热议问题