Properties are a new feature in Objective-C that encapsulates data in objects. There are two main concepts: IVAR (instance variable) and fetch method.

@property = ivar + getter (+ setter); // Read-only attributes have only gettersCopy the code

Property in Runtime is objc_property_t defined as follows:

typedef struct objc_property *objc_property_t;
struct property_t {
    const char * name;
    const char * attributes;
};
Copy the code

Name is the name of the attribute, and Attributes include: type, memory semantics, atomicity, and corresponding instance variables, but not all of them. An 🌰 :

@property (nonatomic,copy) NSString *str;
// name:str attributes:T@"NSString",C,N,V_str
@property (atomic,assign) NSInteger num;
// name:num attributes:Tq,V_num
Copy the code

The key is the type of the attribute. For object types, you can use isKindOfClass, but for data types, you can use the type in attributes. List some common types:

NSInteger,long     Tq,N,V_
NSUInteger         TQ,N,V_
CGFloat,double     Td,N,V_
float              Tf,N,V_
int                Ti,N,V_
bool               TB,N,V_
CGRect T{CGRect={CGPoint=dd}{CGSize=dd}},N,V_rect
CGPoint T^{CGPoint=dd},N,V_point
Copy the code

Once the attributes are defined, the compiler automatically writes the methods needed to access them, a process called autosynthesis. This process is performed by the compiler at compile time.

At sign property has two words for it,

  • @synthesize: The compiler automatically adds setter and getter methods
  • @dynamic: Disables the compiler from automatically adding setter and getter methods

If at sign synthesize and at sign dynamic don’t write, then the default is

@syntheszie var = _var;
Copy the code

@syntheszie usage scenario

Manually implementing setter methods and getters (or overwriting getters for read-only properties)

@interface Test : NSObject
@property (nonatomic,copy,readonly) NSString *name;
@property (nonatomic,assign) NSInteger age;
@end
@implementation Test
@synthesize age = _age;
@synthesize name = _name;
- (void)setAge:(NSInteger)age {
    _age = age;
}
- (NSInteger)age {
    return _age;
}
- (NSString *)name {
    return _name;
}
@end
Copy the code

Implements the properties defined in @protocol

@protocol TestProtocol <NSObject> @property (nonatomic,assign) NSInteger age; @end @interface Test : NSObject<TestProtocol> @end @implementation Test @synthesize age = _age; //@synthesize age; // The member variable name is age@endCopy the code

Overrides a property of a parent class

@interface Super : NSObject
@property(nonatomic,assign) NSInteger age;
@end

@implementation Super
- (instancetype)init {
    self = [super init];
    if (self) {
        _age = 10;
    }
    return self;
}
@end

@interface Test : Super {
    NSInteger _testAge;
}
@end

@implementation Test
@synthesize age = _testAge;
- (instancetype)init{
    self = [super init];
    if (self) {
        _testAge = 20;
    }
    return self;
}
@end
Copy the code