现在的位置: 首页 > 综合 > 正文

解析Obj-C中的assgin,copy,retain关键字的含义。

2018年02月02日 ⁄ 综合 ⁄ 共 2289字 ⁄ 字号 评论关闭

在objc中引入了引用计数的概念Reference counting,当一个对象的计数为0时由系统负责释放对象的内存,每多一次对象引用计数就会加1.

retain:对一个对象引用加1

relese:引用减1

assign:对于非NSObject类型的对象赋值通常采用assign(简单赋值,不更改计数)例如:NSInteger,float,double,char等。

【ARC】

ARC自动引用计数:引入了新的对象生命周期限定(零弱引用:计数为0时自动设置为nil,防止了野指针),新加了strong和weak关键字。strong代替retain,weak代替assign。

weak声明一个当对象消失后指针可以自动设置为nil的对象。


readonly:表示对象是只读的,即仅实现getter操作。

readwrite:可供访问getter,setter

注:self.name=@"hello"和name="hello"的区别是:

1.self.name调用了setName方法,引用会加1.

2.name是直接赋值,引用不变


nonatomic:非原子操作(原子操作主要用在线程之间同步,原子操作是不可拆分的)

atomic:原子操作


【浅拷贝/深拷贝】

copy:对象拷贝,建立一个相同的对象,旧对象不变。不同的地址,但是数据相同,初始计数为1。

mutablecopy:同样是拷贝,只不过复制的是mutable类型的对象例如:NSMutableString。

具体区别:

1.对于非容器类对象:NSString等。

copy是浅拷贝,只复制指针,地址不变(浅拷贝)。mutablecopy是真正的内存复制(深拷贝)。

2.对于容器类对象:NSMutableString等

copy和mutablecopy都是内存复制(深拷贝),但是copy出来的对象不可增加。


但是对于NSArray和NSMutableArray对象来说,copy和mutablecopy都只是复制Array对象,但是对于Array内的内容对象来说并没有复制内存。如果要想实现NSMutableArray的完全拷贝就要用下面的代码,看例子:

NSArray *array = [[NSArray alloc]initWithObjects:[NSMutableString stringWithString:@"one1"],@"two2"];


NSArray *arrayCopy = [[NSArray alloc]initWithArray:array copyItems:YES];


NSArray *arrayDeepCopy = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:array]];

对于arrayCopy而言:@“one1”是内存赋值了,可@“two2”却没有内存赋值还是指针拷贝。只有arrayDeepCopy才是真正的完全内存复制。新的arryDeepCopy内的所有内容对象都是新的内存。


》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》

另一个问题:如何对自定义的对象使用copy和mutablecopy呢?

答:只用自己实现:copyWithZone或mutableCopyWithZone函数就可以使用copy或mutableCopy了。

@interface MyObj : NSObject<NSCopying,NSMutableCopying>
{
         NSMutableString *name;
         NSString *imutableStr;
         int age;
}
@property (nonatomic, retain) NSMutableString *name;
@property (nonatomic, retain) NSString *imutableStr;
@property (nonatomic) int age;
@end
@implementation MyObj
@synthesize name;
@synthesize age;
@synthesize imutableStr;
- (id)init
{
         if (self = [super init])
         {
                   self.name = [[NSMutableString alloc]init];
                   self.imutableStr = [[NSString alloc]init];
                   age = -1;
         }
         return self;
}
- (void)dealloc
{
         [name release];
         [imutableStr release];
         [super dealloc];
}
- (id)copyWithZone:(NSZone *)zone
{
         MyObj *copy = [[[self class] allocWithZone:zone] init];
         copy->name = [name copy];
         copy->imutableStr = [imutableStr copy];
//       copy->name = [name copyWithZone:zone];;
//       copy->imutableStr = [name copyWithZone:zone];//
         copy->age = age;
         return copy;
}
- (id)mutableCopyWithZone:(NSZone *)zone
{
         MyObj *copy = NSCopyObject(self, 0, zone);
         copy->name = [self.name mutableCopy];
         copy->age = age;
         return copy;
}

【上篇】
【下篇】

抱歉!评论已关闭.