NSMutableDictionary与copy 问题举例【入门
2020-03-12 本文已影响0人
码农二哥
场景1
- 示例代码如下:
@interface WPersion : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
@implementation WPersion
-(NSString *)description
{
return [NSString stringWithFormat:@"name:%@, age:%@", _name, @(_age)];
}
@end
- 执行以下代码有啥问题呢?
{
NSMutableDictionary *md = [[NSMutableDictionary alloc] init];
[md setObject:@"123" forKey:@"str"];
WPersion *persion = [[WPersion alloc] init];
persion.name = @"name";
persion.age = 10;
[md setObject:persion forKey:@"obj"];
NSMutableDictionary *mmd = [[NSMutableDictionary alloc] initWithDictionary:md copyItems:YES];
}
- 答:WPersion没有实现copy协议,无法copy,会crash。
场景2
- WPersion代码不变,如下:
@interface WPersion : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
@implementation WPersion
-(NSString *)description
{
return [NSString stringWithFormat:@"name:%@, age:%@", _name, @(_age)];
}
@end
- 执行以下代码有啥问题呢?
@interface ViewController ()
@property (nonatomic, copy) NSMutableDictionary *mdict;
@end
...
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
{
NSMutableDictionary *md = [[NSMutableDictionary alloc] init];
[md setObject:@"123" forKey:@"str"];
WPersion *persion = [[WPersion alloc] init];
persion.name = @"name";
persion.age = 10;
[md setObject:persion forKey:@"obj"];
self.mdict = md;
}
[_mdict setObject:@"456" forKey:@"str1"];
}
...
- 答:self.mdict = md时,进行了copy操作,返回值是NSDictonary,不能修改(setObject:forKey:),会crash。