Objective-C

[14일차]객체의 복사

에너지발전소 2010. 5. 26. 20:28
* 얕은복사
int *p = (int *)malloc(4);
int *q = p;
*p = 10;
printf("%d",*p);
printf("%d",*q);
*p =20;
printf("%d",*q);


* 깊은복사
int*p=(int *)malloc(4);
*p=10;
int *q = (int*) malloc(4);
*q=*p;
printf("%d",*p);
printf("%d",*q);
*p=20;
printf("%d",*q);

ex)copy와 mutablecopy는 얕은복사
#import <foundation/NSObject.h>
#import <foundation/NSArray.h>
#import <foundation/NSString.h>
#import <foundation/NSAutorelease.h>
int main()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    NSMutalbeArray * ar1 = [NSMutalbeArray arrayWithObjects:[NSMutableString:@"1"],[NSMutableString:@"2", [NSMutableString:@"3"],nil];
NSMutableArray *ar2;
NSMutalbeString *str;
int i;
NSLog(@"ar 1의 요소");
NSLog(@"--------");
for(i=0; i<[ar1 count];i++)
    NSLog(@"%d",[ar1 objectAtIndex: i]);
    ar2=[ar1 mutableCopy]; 
    str=[ar1 objectAtIndex:0];
    [str app;endString:@"1"];
    NSLog(@"---------");
    NSLog(@"ar2의 요소");
    NSLog(@"---------");
    for(i=0;i[ar2 count];i++)
        NSLog(@"%@",[ar2 objectAtIndex:i]);

[ar1 release];
[ar2release];
[pool drain];
system("pause");
return 0;
}

3. Copy의 구현
=>NSObject 클래스의 NSCopying프로토볼이 선언
=>NSObject 클래스에는 실제구현되어 있지 않음
   이 메서드는 내부적으로
  -(id)copyWithZone:(NSZone *)
                             //heap에 관련된 클래스0
                                메모리할당시 allocwinthzone: nose객체를 이용하면 비슷한 경험이 생김

따라서 copy메서드를 사용하고자 하는 경우 위의 메서드를 출현