• preface

    Since the introduction of property Autosynthesis by the LLVM compiler in iOS 6, synthesize is rarely used, and dynamic is rarely used, except in special situations.

role

@property produces an underlined member variable,set/get method declaration and implementation. At sign synthesize will generate a member variable with the same name as the implementation of the set/get method. You can also specify a property that binds the member variable to the @synthesize property = @dynamic member variable and tell the compiler the set/get method and I’ll do that myself.

@synthesize property = member variable usage scenario

Protocol because the properties in Protocol, there’s only getters and setters, there’s no member variables, so the synthesize would produce the getter method, the setter method, and a member variable 2 by default. Overwriting a member property declared with @property in both the setter and getter methods automatically generates the setter The getter method, if you override the set and get methods, the member property declared with @property is not a member property, it’s another instance variable, and that instance variable needs to be declared manually. So you get an error. 3. If the property is modified by readonly, the getter is overridden

The sample

@property

@interface CViewController(a)
@property (nonatomic , copy) NSString *name;
@end  
Copy the code

The ////property does the equivalent of generating an _name member variable,setName,name method declaration and implementation. Equivalent to ⬇

@interface CViewController(a){
    NSString *_name;
}
- (void)setName:(NSString *)name;
- (NSString *)name;
@end

@implementation CViewController- (void)setName:(NSString*)name{ _name = name; } - (NSString *)name{
    return _name;
}
@end
Copy the code

@synthesize

@interface CViewController(a)
@property (nonatomic , copy) NSString *name;
@end  
@implementation CViewController
@synthesize name;
@end
Copy the code

What synthesize does is it generates a member variable with the same name name,set and get method declaration and implementation. Why is the underscore name not generated? Because the property will do one thing when it sees that there is no member variable it will generate a member variable called _name, and then it will call @synthesize name = _name, and put _name in the setter and getter of name. Because we’re writing at sign synthesize name, we’re not going to generate the _name variable.

@interface CViewController(a)
{
    NSString*name; } - (void)setName:(NSString*)newName; - (NSString *)name;
@end

@implementation CViewController
@synthesizename; - (void)setName:(NSString*)newName{ name = newName; } - (NSString *)name{
    return name;
}
@end
Copy the code