首页 > 代码库 > copy and mutableCopy

copy and mutableCopy

结论:

 

技术分享

 

1, 深复制与浅复制

 

技术分享

 

 

 2,immutable和mutable

 

技术分享

 

3,代码分析:
 

#pragma mark - String

- (void)stringCopyAndMutableCopy {
    NSString *originStr = @"123";
    NSString *copyStr = [originStr copy];//浅复制
    NSString *mutableCopyStr = [originStr mutableCopy];//深复制
    NSLog(@"string origin = %p, copy = %p, mutableCopy = %p", originStr, copyStr, mutableCopyStr);
    NSLog(@"str copy class = %s, mutableCopy class = %s", object_getClassName(copyStr), object_getClassName(mutableCopyStr));
}

- (void)mutableStringCopyAndMutableCopy {
    NSMutableString *originMutableStr = [NSMutableString stringWithString:@"123"];
    NSString *copyMutableStr = [originMutableStr copy];// 深复制
    NSString *mutableCopyMutableStr = [originMutableStr mutableCopy];//深复制
    NSLog(@"mutableStr origin = %p, copy = %p, mutableCopy = %p", originMutableStr, copyMutableStr, mutableCopyMutableStr);
    NSLog(@"mutableStr copy class = %s, mutableCopy class = %s", object_getClassName(copyMutableStr), object_getClassName(mutableCopyMutableStr));
}

#pragma mark - Array

/**
 *
 *  __NSArrayM->NSMutableArray->NSArray
 *  __NSArrayI->NSArray
 */


- (void)arrayCopyAndMutableCopy {
    NSArray *orginArray = @[@"123"];
    NSArray *copyArray = [orginArray copy];
    NSArray *mutableCopyArray = [orginArray mutableCopy];
    NSLog(@"array origin = %p, copy = %p, mutableCopy = %p", orginArray, copyArray, mutableCopyArray);
    NSLog(@"array copy class = %s, mutableCopy class = %s", object_getClassName(copyArray), object_getClassName(mutableCopyArray));
}

- (void)mutableArrayCopyAndMutableCopy {
    NSMutableArray *orginMutableArray = [NSMutableArray arrayWithObject:@"123"];
    NSArray *copyMutableArray = [orginMutableArray copy];
    NSArray *mutableCopyMutableArray = [orginMutableArray mutableCopy];
    NSLog(@"mutableArray origin = %p, copy = %p, mutableCopy = %p", orginMutableArray, copyMutableArray, mutableCopyMutableArray);
    NSLog(@"mutableArray copy class = %s, mutableCopy class = %s", object_getClassName(copyMutableArray), object_getClassName(mutableCopyMutableArray));
}

 

示例代码:https://github.com/shilihuan/CopyAndMutableCopy

 

copy and mutableCopy