美文网首页
NSMutableDictionary与copy 问题举例【入门

NSMutableDictionary与copy 问题举例【入门

作者: 码农二哥 | 来源:发表于2020-03-12 08:01 被阅读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。

    相关文章

      网友评论

          本文标题:NSMutableDictionary与copy 问题举例【入门

          本文链接:https://www.haomeiwen.com/subject/rgjejhtx.html