IOS에서 copy 분석

3209 단어
copy에는 copy와 mutable Copy가 있습니다.
string에는 NSString NSMutableString이 있습니다.
NSString 의 약관은 다음과 같습니다.

        NSString *string = [NSString stringWithFormat:@"test"];
        NSLog(@"   =%ld  %p",[string retainCount],string);
        NSString *copyString = [string  copy];
        NSLog(@"   =%ld  %p",[string retainCount],string);
        NSLog(@"     =%ld  %p",[copyString retainCount],copyString);

테스트 결과는 다음과 같다.

2015-07-30 11:02:26.875 09-test[643:303]    =1  0x100108f30
2015-07-30 11:02:26.877 09-test[643:303]    =2  0x100108f30
2015-07-30 11:02:26.878 09-test[643:303]      =2  0x100108f30

NSString의 깊이는 다음과 같습니다.

 NSString *string = [NSString stringWithFormat:@"test"];
        NSLog(@"     =%ld  %p",[string retainCount],string);
        NSString *copyString = [string  mutableCopy];
        NSLog(@"     =%ld  %p",[string retainCount],string);
        NSLog(@"       =%ld  %p",[copyString retainCount],copyString);

테스트 결과는 다음과 같습니다.

2015-07-30 11:06:56.875 09-test[681:303]      =1  0x1002026d0
2015-07-30 11:06:56.877 09-test[681:303]      =1  0x1002026d0
2015-07-30 11:06:56.878 09-test[681:303]        =1  0x100204400

NSMutableString의 간단한 복제

       NSMutableString *string = [NSMutableString stringWithFormat:@"test"];
        NSLog(@"   =%ld  %p",[string retainCount],string);
        NSMutableString *copyString = [string  copy];
        NSLog(@"   =%ld  %p",[string retainCount],string);
        NSLog(@"     =%ld  %p",[copyString retainCount],copyString);

결과 복사

2015-07-30 11:12:31.772 09-test[694:303]    =1  0x100204340
2015-07-30 11:12:31.775 09-test[694:303]    =1  0x100204340
2015-07-30 11:12:31.775 09-test[694:303]      =1  0x1003017c0

NSMutableString의 딥 클로닝

    NSMutableString *string = [NSMutableString stringWithFormat:@"test"];
        NSLog(@"     =%ld  %p",[string retainCount],string);
        NSString *copyString = [string  mutableCopy];
        NSLog(@"     =%ld  %p",[string retainCount],string);
        NSLog(@"       =%ld  %p",[copyString retainCount],copyString);

복제 결과:

2015-07-30 11:15:06.882 09-test[706:303]      =1  0x10010b1a0
2015-07-30 11:15:06.884 09-test[706:303]      =1  0x10010b1a0
2015-07-30 11:15:06.885 09-test[706:303]        =1  0x100401b70

요약은 다음과 같습니다.
1. 변할 수 없는 String 얕은 복사(copy)가 복사 주소인 경우 두 대상이 인용하는 주소 계수기가 있으면 당연히 1을 더해야 하고 주소가 같다
2. 불변String 깊이 복제(mutable Copy)는 복제 대상의 내용입니다.내용을 복제한 이상 원래의 대상(복제된 대상)은 내용만 제공하고, 인용계수기는 추가할 필요가 없다. 복제된 대상은 새로운 대상이고, 주소는 새로운 주소이다.
3. 가변 스트링 얕은 복제와 깊은 복제에 대해 나는 이렇게 이해한다. 그 가변성은 깊은 복제와 상관없이 새로운 대상을 너에게 되돌려줄 수 있기 때문이다.

좋은 웹페이지 즐겨찾기