对于初学的开发者,对于assign、retain、copy、strong、weak的用法及意义可能不是很明白,我对于这个问题也研究了很久,写篇博文,巧巧代码,让我们来瞧瞧吧!
先定义一个Student类:
#import <Foundation/Foundation.h>
@interface Student : NSObject
@property (nonatomic, copy) NSString *name;
@end
然后先是mrc下的assign声明
@property (nonatomic, assign) Student *stu1;
接下来初始化一个Student对象,并且敲入以下代码
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Student *stu = [[Student alloc] init];
stu.name = @"张三";
self.stu1 = stu;
NSLog(@"%p %p", &stu, &_stu1);
NSLog(@"%p %p", stu,_stu1);
self.stu1.name = @"李四";
NSLog(@"stu.name = %@", stu.name);
NSLog(@"stu的引用计数 = %ld", [stu retainCount]);
}
控制台输出
(一)所以我总结,assign只是使指向stu的栈内存上的的指针,也就是stu换了一个名字,换成了stu1,就是stu和stu1的作用和意义是一样的,谁做了任何改变对应的指向栈内存的内容也会随之改变,但是栈内存的引用计数还是1没有增加。
接下来我们看看retain,改变stu1属性为以下
@property (nonatomic, retain) Student *stu1;
然后重新运行程序控制台输出为:
(二)再来总结一下,retain是使指向栈内存的指针多了一个,也就是引用计数加1,并且指针stu和stu1对于栈内存的作用是一样的,也就是一扇门多了一把钥匙
接下来再看看copy的作用,同样改变stu属性为copy,但是如果是我们定义的对象,那么我们自己要实现NSCopying,这样就能调用copy,贴出代码
Student.h
#import <Foundation/Foundation.h>
@interface Student : NSObject<NSCopying>
@property (nonatomic, copy) NSString *name;
@end
Student.m
#import "Student.h"
@implementation Student
- (id)copyWithZone:(NSZone *)zone
{
Student *stuCopy = [[</span><span class="s3">self</span><span class="s1"> </span><span class="s4">class</span><span class="s1">] </span><span class="s4">allocWithZone</span><span class="s1">:zone];</span></p><p class="p1"><span class="s1"> stuCopy.</span><span class="s5">name</span><span class="s1"> = [</span><span class="s3">self</span><span class="s1">.</span><span class="s5">name</span><span class="s1"> </span><span class="s4">copyWithZone</span><span class="s1">:zone];</span></p><p class="p1"><span class="s1"> </span><span class="s3">return</span><span class="s1"> stuCopy;</span></p>}
@end