不务正业之OC(十)–复制对象之retain与copy区别

复制对象:创建一副本,开辟一块新的内存空间
实现协议:NSCopying或NSMutableCopying其中之一
注意:Copy产生对象不可变、MutableCopy产生对象可变

//  main.m
//  Objcopy
 
#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[])
{
 
    @autoreleasepool {
        NSMutableArray *muarray = [NSMutableArray arrayWithObjects:@"a",@"b",@"c",nil];
        NSMutableArray *retain_array = [muarray retain];
        [retain_array removeLastObject];
        for (NSString *member in muarray){
            NSLog(@"member is %@",member);
        }
        NSLog(@"retain count %lu",(unsigned long)muarray.retainCount);
        [muarray release];
        NSLog(@"retain count %lu",(unsigned long)muarray.retainCount);
 
        NSLog(@"-----------------------");
        NSMutableArray *muarray2 = [NSMutableArray arrayWithObjects:@"a",@"b",@"c",nil];
        NSMutableArray *copy_array = [muarray2 mutableCopy];
        [copy_array removeLastObject];
        for (NSString *member in muarray2){
            NSLog(@"member is %@",member);
        }
 
    }
    return 0;
}

Copy和NSMutableCopy区别

#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[])
{
 
    @autoreleasepool {
        NSArray *array1 = [NSArray arrayWithObjects:@"a",@"b",nil];
        NSMutableArray *array2 = [NSMutableArray arrayWithObjects:@"a",@"b",nil];
        [array1 addObject:"c"];//这行代码直接崩溃
        [array2 addObject:@"c"];
        NSLog(@"%@",array2);
    }
    return 0;
}

Post a Comment