美文网首页iOS开发
iOS Copy 与 MutableCopy

iOS Copy 与 MutableCopy

作者: 当阳桥 | 来源:发表于2017-02-06 19:40 被阅读66次

    用不可变容器类创建的对象 进行的copy 是指针复制,没有创建对象,进行的mutableCopy不再是地址拷贝,是全新的对象,容器内的对象还是指针复制

        NSObject *myObj = [[NSObject alloc] init];
        myObj.myTitle = @"my title";
        
        NSObject *myObj2 = [[NSObject alloc] init];
        myObj2.myTitle = @"my title2";
    
        NSObject *myObj3 = [[NSObject alloc] init];
        myObj3.myTitle = @"my title3";
    
        NSArray *array = @[myObj,myObj2,myObj3];
        NSArray *arrayRetain = array;
        NSArray *arrayCopy = array.copy;
        NSMutableArray *mArrayCopy = array.mutableCopy;
        
        NSLog(@"----------------------------------------------------------------------------------");
        NSLog(@"%p-------%@",array,array);
        NSLog(@"%p-------%@",arrayRetain,arrayRetain);
        NSLog(@"%p-------%@",arrayCopy,arrayCopy);
        NSLog(@"%p-------%@",mArrayCopy,mArrayCopy);
    
    

    用可变的容器创建的对象 进行copy,mutableCopy不是指针复制,都是创建了全新的对象,容器内的对象还是指针复制

        NSMutableArray *mArray = [NSMutableArray arrayWithArray:@[myObj,myObj2,myObj3]];
        
        NSArray *arrayRetain = mArray;
        NSArray *arrayCopy = mArray.copy;
        NSMutableArray *mArrayCopy = mArray.mutableCopy;
    
        NSLog(@"----------------------------------------------------------------------------------");
        NSLog(@"%p-------%@",mArray,mArray);
        NSLog(@"%p-------%@",arrayRetain,arrayRetain);
        NSLog(@"%p-------%@",arrayCopy,arrayCopy);
        NSLog(@"%p-------%@",mArrayCopy,mArrayCopy);
        
        NSLog(@"----------------------------------------------------------------------------------");
        [mArray removeAllObjects];
        NSLog(@"%p-------%@",mArray,mArray);
        NSLog(@"%p-------%@",arrayRetain,arrayRetain);
        NSLog(@"%p-------%@",arrayCopy,arrayCopy);
        NSLog(@"%p-------%@",mArrayCopy,mArrayCopy);
    
        NSArray *array = [NSMutableArray arrayWithArray:@[myObj,myObj2,myObj3]];
    
    

    不可变的非容器类对象 copy 只是地址复制。mutableCopy不是地址复制,创建了新的对象

        NSString *string = @"string";
        NSString *stringCopy = string.copy;
        NSMutableString *mStringCopy = string.mutableCopy;
        
        NSLog(@"%p-------%@",string,string);
        NSLog(@"%p-------%@",stringCopy,stringCopy);
        NSLog(@"%p-------%@",mStringCopy,mStringCopy);
    

    可变的非容器类对象copy 、mutableCopy不是地址复制,创建了新的对象

        NSString *mString = [NSMutableString stringWithString:@"string"];
        NSString *stringCopy = mString.copy;
        NSMutableString *mStringCopy = mString.mutableCopy;
        
        NSLog(@"%p-------%@",mString,mString);
        NSLog(@"%p-------%@",stringCopy,stringCopy);
        NSLog(@"%p-------%@",mStringCopy,mStringCopy);
    

    相关文章

      网友评论

        本文标题:iOS Copy 与 MutableCopy

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