OC 之 Property

2019-12-11  本文已影响0人  张_何

介绍

特质

原子性相关

atomic
- (void)setAtomicObj:(NSObject *)atomicObj{
    @synchronized(self) { // 同步锁
        if (_atomicObj != atomicObj) {
            [_atomicObj release];
            _atomicObj = [atomicObj retain];
        }
    }
}
- (NSObject *)atomicObj{
    @synchronized(self) {// 同步锁
        return _atomicObj;
    }
}
nonatomic

内存管理相关

copy
assign

Specifies that the setter uses simple assignment. This attribute is the default. You use this attribute for scalar types such as NSInteger and CGRect.

// 使用 strong 修饰时
-(void)setName:(NSString *) name {
    if(name != _name){
      [_name release];
      _name = [name retain];
    }
} 
// 使用 assign 修饰时
-(void)setName:(NSString *) name {
      _name = name;
} 

weak
weak 的原理

1、当使用 weak 关键字初始化一个弱引用对象时,会调用id objc_initWeak(id *location, id newObj) 函数该函数内部调用static id storeWeak(id *location, objc_object *newObj) 函数,location代表weak 指针的地址,newObj 是被weak引用的对象。这个函数会根据对象的地址值获取 SideTables 中对应的 sideTable,更具获取的 sideTable 取出sideTable中的weak_table_t,weak_table_t 中存放着一个 weak_enter_t类型的hash 数组,然后会将对象和弱引用对象的地址包装成weak_enter_t类型的结构体,存放到weak_enter_t类型的hash 数组中,当弱引用的对象被释放时,dealloc ->_objc_rootDealloc-> object_dispose -> objc_destructInstance -> objc_clear_deallocating, 最后objc_clear_deallocating函数中会判断对象是否被弱引用过,如果是,就去 sideTable 中的 weak_table_t的 weak_entery_t 类型的列表中找对该对象对应的weak_entery_t然后将里面存放弱引用该对象的地址列表全部置为 nil, 然后将该weak_entery_t从 sideTable 中移除.

strong
unsafe_unretained
@property (nonatomic, unsafe_unretained) NSInteger count;
@property (nonatomic, unsafe_unretained) NSString *home;

读写相关

方法名

值相关

延伸

类属性

上一篇 下一篇

猜你喜欢

热点阅读