时不时会有点迷惑属性修饰符retain、strong、copy三者之间的区别,还是把测试过程记录下来好一点!

1、属性修饰符结论

2、给retain、strong、copy修饰的字符串属性赋值指针变化测试例子

3、字符串调用copy、mutableCopy方法给字符串赋值指针变化例子

 

一、属性修饰符retain、strong、copy修饰字符串测试

先看代码,创建一个Person类,定义属性

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property (nonatomic, retain) NSString *strRetain;
@property (nonatomic, strong) NSString *strStrong;
@property (nonatomic, copy) NSString *strCopy;
@property (nonatomic, retain) NSMutableString *strMutableRetain;
@property (nonatomic, strong) NSMutableString *strMutableStrong;
@property (nonatomic, copy) NSMutableString *strMutableCopy;

@end

测试代码:

 1 Person *per = [[Person alloc] init];
 2     NSString *name = @"原XM";
 3     [per setStrRetain:name];
 4     [per setStrStrong:name];
 5     per.strCopy = name;
 6     
 7     NSMutableString *name2 = [[NSMutableString alloc] initWithString:@"原XM2"];
 8     per.strMutableRetain = name2;
 9     per.strMutableStrong = name2;
10     per.strMutableCopy = name2;
11     
12     NSLog(@"------ 改变之前打印 ------");
13     NSLog(@"per.strRetain: %@, ", per.strRetain);
14     NSLog(@"per.strStrong: %@", per.strStrong);
15     NSLog(@"per.strCopy: %@", per.strCopy);
16     NSLog(@"per.strMutableRetain: %@", per.strMutableRetain);
17     NSLog(@"per.strMutableStrong: %@", per.strMutableStrong);
18     NSLog(@"per.strMutableCopy: %@", per.strMutableCopy);
19     
20     name = @"新XM";
21     [name2 appendString:@"新XM2"];
22     
23     NSLog(@"------- 改变之后打印 -------");
24     NSLog(@"per.strRetain: %@", per.strRetain);
25     NSLog(@"per.strStrong: %@", per.strStrong);
26     NSLog(@"per.strCopy: %@", per.strCopy);
27     NSLog(@"per.strMutableRetain: %@", per.strMutableRetain);
28     NSLog(@"per.strMutableStrong: %@", per.strMutableStrong);
29     NSLog(@"per.strMutableCopy: %@", per.strMutableCopy);
View Code

相关文章:

  • 2022-12-23
  • 2021-10-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-25
  • 2022-12-23
  • 2021-12-24
猜你喜欢
  • 2021-10-17
  • 2022-12-23
  • 2021-06-27
  • 2021-06-08
  • 2022-12-23
  • 2022-02-08
  • 2022-12-23
相关资源
相似解决方案