场景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
@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。
网友评论