IOS에서 객체의 사용법 및 깊이 및 얕은 복사 설명

9387 단어
첫째, 복제 대상의 기본 개념
하나의 대상을 복사본으로 복사하고, 새로운 메모리를 개척하여 복사본 대상을 저장합니다.
둘째, 만약에 대상이 복제 기능을 갖추려면 반드시 협의와 협의를 실현해야 한다.
NSObject 자체가 가지고 있는 상용 대상은 NSNumber, NSString, NSArray, NSDictionary, NSMutableArray, NSMutableDictionay, NSMutableString이다. copy가 생성한 대상은 변할 수 없고mutableCopy가 생성한 대상은 변할 수 있다.
셋째,retain과copy의 차이
    @autoreleasepool {
        NSMutableArray *array=[NSMutableArray arrayWithObjects:@"one",@"two",@"three",@"four",nil];
        NSMutableArray *retainArray=[array retain];
        [retainArray removeLastObject];
        for(NSString *str in array)
        {
            NSLog(@"the part is %@",str);
        }
        NSLog(@"the retaincount is %ld",[retainArray retainCount]);
        // insert code here...
        NSLog(@"Hello, World!");
        
    }


결과:
2014-05-19 10:58:22.639 objective[1095:303] the part is one
2014-05-19 10:58:22.641 objective[1095:303] the part is two
2014-05-19 10:58:22.641 objective[1095:303] the part is three
2014-05-19 10:58:22.641 objective[1095:303] the retaincount is 2
NSMutableArray *array=[NSMutableArray arrayWithObjects:@"one",@"two",@"three",@"four",nil];
        NSMutableArray *retainArray=[array mutableCopy];
        [retainArray removeLastObject];
        for(NSString *str in array)
        {
            NSLog(@"the part is %@",str);
        }
        NSLog(@"the retaincount is %ld",[retainArray retainCount]);

결실
2014-05-19 10:59:03.826 objective[1104:303] the part is one
2014-05-19 10:59:03.828 objective[1104:303] the part is two
2014-05-19 10:59:03.828 objective[1104:303] the part is three
2014-05-19 10:59:03.829 objective[1104:303] the part is four
2014-05-19 10:59:03.829 objective[1104:303] the retaincount is 1
넷째, COPY와 Mutable Copy의 차이점
COPY는 불변 객체의 복사본을 반환하고 MutalbeCopy는 불변 객체의 복사본을 반환합니다.
        NSArray *array=[NSArray arrayWithObjects:@"one",@"two", nil];
        NSMutableArray *array1=[array copy];
        [array1 addObject:@"three"];  //error
        NSMutableArray *array2=[array mutableCopy];
        [array2 addObject:@"three"];  //right
        // insert code here...
        NSLog(@"Hello, World!");

다섯째, 얕은copy와 진한copy
얕은 복제는 대상 자체를 복제하고 대상의 속성, 포함된 대상은 복제하지 않는다
객체의 속성 및 기타 객체를 포함하여 전체 복사하기
Foundation 프레임워크는 복제를 지원하는 클래스입니다. 기본값은 얕은 복제입니다.
        NSMutableArray *array=[[NSMutableArray alloc] init];
        for(int i=0;i<3;i++)
        {
            NSObject *obj=[[NSObject alloc] init];
            [array addObject:obj];
            [obj release];
        }
        for(NSObject *obj1 in array)
        {
            NSLog(@"    %p,      %ld",obj1,obj1.retainCount);
        }
        NSMutableArray *array2=[array copy];
        for(NSObject *obj2 in array2)
        {
            NSLog(@"    %p,      %ld",obj2,obj2.retainCount);
        }
2013-09-30 17:28:01.492 FDAS[681:303]     0x1001081f0,      1
2013-09-30 17:28:01.506 FDAS[681:303]     0x100108230,      1
2013-09-30 17:28:01.506 FDAS[681:303]     0x100108240,      1
2013-09-30 17:28:01.507 FDAS[681:303]     0x1001081f0,      2
2013-09-30 17:28:01.507 FDAS[681:303]     0x100108230,      2
2013-09-30 17:28:01.507 FDAS[681:303]     0x100108240,      2

다섯째, 대상의 사용자 정의 복사본
대상은 복제 기능이 있어 NSCopying, NSMutable Copying 프로토콜, 이 프로토콜을 실현하는 copy WithZone 방법과 mutable Copy WithZone 방법을 실현해야 한다.
딥 카피와 얕은 카피의 차이는 copyWithZone 방법의 실현에 있다.
간단한 복사 코드는 다음과 같습니다.
#import 

@interface Person : NSObject
@property(nonatomic,retain)NSString *name;
@property(nonatomic,retain)NSString *age;

@end
#import "Person.h"

@implementation Person

- (id)copyWithZone:(NSZone *)zone
{
   //        
    Person *person=[[self class] allocWithZone:zone];
    person.age=_age;
    person.name=_name;
    return person;
}
@end

main 함수는 다음과 같습니다.
    @autoreleasepool {
        
        Person *person=[[Person alloc] init];
        person.name=@"andy";
        person.age=@"20";
        
        Person *person2=[person copy];
        NSLog(@"person    %p,person2   %p",person.name,person2.name);
    }

출력 결과:
2013-09-30 17:48:41.007 FDAS[732:303] person    0x1000022c8,person2   0x1000022c8

깊이 복사 코드는 다음과 같습니다.
- (id)copyWithZone:(NSZone *)zone
{
   //        
    Person *person=[[self class] allocWithZone:zone];
    person.age=[_age copy];
    person.name=[_age copy];
    return person;
}

결과:
2013-09-30 17:55:13.603 FDAS[742:303] person    0x1000022c8,person2   0x1000022e8
        NSArray *arr=[NSArray arrayWithObjects:@"one",@"two",nil];
        NSArray *arr2=[arr copy];
        NSLog(@"the dress of arr is %p the dress of arr2 is %p",arr,arr2);
        NSLog(@"the retainCount is %ld",arr.retainCount);


실행 결과는 다음과 같습니다.
2013-09-30 18:01:01.394 FDAS[787:303] the dress of arr is 0x100108320 the dress of arr2 is 0x100108320
2013-09-30 18:01:01.396 FDAS[787:303] the retainCount is 2
결과는 같다. Foundation이 변할 수 없는 복제 대상에 대해 copy 방법이 최적화되었기 때문에retain에 해당하기 때문에retaincount는 2.
copyWithZone 메서드에서:return [self retain],
여섯째,copy,mutableCopy와retain의 관계
Foundation 대상에서 copy가 변할 수 없는 대상일 때retain
mutableCopy를 사용할 때 원본 대상이 변할 수 있든 없든 간에 복사본은 변할 수 있고 진정한 의미의copy를 실현한다
복사 대상을 사용할 때 복사 대상은 변할 수 없습니다.
딥 카피 및 얕은 카피 정보:
첫째, 간단한 복사:
    Car *car=[[[self class] allocWithZone:zone] init];
    car.engine=_engine;
    car.name=_name;
    car.weight=_weight;
    return car;

테스트 코드:
 Car *car = [[Car alloc] init];
        Engine *engine = [[Engine alloc] init];
        car.engine = engine;
        [engine release];
        //NSLog(@"engine retaincount is %lu",[engine retainCount]);
        car.name = @"  ";
        car.weight = @1000;

        Car *car2=[car copy];
       // NSLog(@"car2 retaincount is %lu",[car2 retainCount]);
        NSLog(@"car %@,car2:%@",car.engine,car2.engine);

결과 출력:
카, 카2: 얕은 복제는 복제 바늘일 뿐 새로운 메모리 공간을 만들지 않았다는 것을 알 수 있다.
둘째, 딥 카피:
- (id)copyWithZone:(NSZone *)zone {
    /***   **/
    Car *car=[[[self class] allocWithZone:zone] init];
    Engine *engineCopy=[[_engine copy] autorelease];
    car.engine=engineCopy;
    
    NSString *namecopy=[[_name copy] autorelease];
    car.name=namecopy;
    
    NSNumber *weightcopy=[[_weight copy] autorelease];
    car.weight=weightcopy;
    return car;
}

테스트 코드:
Car *car = [[Car alloc] init];
        Engine *engine = [[Engine alloc] init];
        car.engine = engine;
        [engine release];
        //NSLog(@"engine retaincount is %lu",[engine retainCount]);
        car.name = @"  ";
        car.weight = @1000;

        Car *car2=[car copy];
       // NSLog(@"car2 retaincount is %lu",[car2 retainCount]);
        NSLog(@"car %@,car2:%@",car.engine,car2.engine);

결과:
카, 카2: 새로운 공간을 개척했다.zone는 하나의 메모리 공간을 대표한다
 Car *car=[[[self class] allocWithZone:zone] init];

상기 코드는 [self class]를 사용한 것이지 카를 사용한 것이 아닙니다. 카를 사용한 경우 카의 하위 클래스가 이 방법으로copy 프로토콜을 실행할 때 메모리 문제가 발생할 수 있기 때문입니다.
또한 자류가 부류를 계승할 때 그는 부류의 모든 속성을 계승했다. 이는 실현할 협의를 포함한다.
셋째, NSFoundation, 우리가 copy를 할 때 변할 수 없는 대상이 될 때 기본적인 copy는 모두 얕은 복사본으로retain에 해당한다
        NSArray *array =[NSArray arrayWithObjects:@"one",@"two",@"three", nil];
        NSArray *array1 = [array copy];
        NSLog(@"%p",array);
        NSLog(@"%p",array1);
        NSLog(@"the retaincount is %lu",[array retainCount]);

결과 출력:
copyDemo1[673:303] 0x10010a5d0
2013-12-28 20:01:10.969 copyDemo1[673:303] 0x10010a5d0
2013-12-28 20:01:10.969 copy Demo1 [673:303] the retaincount is 2 retaincount 증가 주의
mutableCopy를 사용할 때 대상이 변할 수 있든 없든 깊은 복사를 할 수 있습니다
        NSArray *array =[NSArray arrayWithObjects:@"one",@"two",@"three", nil];
        NSMutableArray *array1 = [array mutableCopy];
        NSLog(@"%p",array);
        NSLog(@"%p",array1);
        NSLog(@"the retaincount is %lu",[array retainCount]);

결과:
copyDemo1[695:303] 0x10010a5d0
2013-12-28 20:07:08.570 copyDemo1[695:303] 0x10010b260
2013-12-28 20:07:08.570 copyDemo1 [695:303] the retaincountis 1 제4,retain은 두 대상이 같은 바늘을 가리키는 것과 같다
        NSMutableArray *array1 = [[NSMutableArray alloc] initWithObjects:@"one",@"two",@"three",@"foure", nil];
        NSMutableArray *array2 = [array1 retain];
        [array2 removeLastObject];
        NSLog(@"%@",array1);
        NSLog(@"the retaincount is %ld",array2.retainCount);
결과:
2013-12-28 20:13:02.915 copyDemo1[736:303] (
    one,
    two,
    three
)
2013-12-28 20:13:02.917 copyDemo1[736:303] the retaincount is 2

좋은 웹페이지 즐겨찾기