今天想学习一下深浅拷贝的问题,于是写了个测试程序,出现了预料之外的结果,十分不解
哪位牛人帮忙解析一下,感激不尽
以下分别为程序;倒数第7、8行有注释和无注释的结果
#include<Foundation/Foundation.h>@interface AUSU:NSObject<NSCopying>
{
   NSString * str;
}
@property(retain,nonatomic) NSString* str;
@end
@implementation  AUSU
@synthesize str;
-(id)copyWithZone:(NSZone *)zone
{
AUSU* cop=[[[self class] allocWithZone:zone] init];
cop.str=[[self.str copyWithZone:zone] autorelease];
return cop;
}
-(void) dealloc
{
[str release];
[super dealloc];
}
@endint main(int argc, char *argv[])
{         NSAutoreleasePool *pool=[[ NSAutoreleasePool alloc] init];    
    NSString* str1=[[NSString alloc] initWithString:@"str1"];
    NSLog(@"str1 retain count is:::%d",[str1 retainCount]);
     AUSU* ausu1=[[AUSU alloc] init];
     NSLog(@"ausu1 retain count is:::%d",[ausu1 retainCount]);
            ausu1.str=str1;
    NSLog(@"afer \"ausu1.str=str1\" retain count is:::%d",[str1 retainCount]);
    [str1 release];     AUSU* ausu2=[ausu1 copy];
    NSLog(@"ausu1 retain count is:::%d",[ausu1 retainCount]);//1
    NSLog(@"ausu2 retain count is:::%d",[ausu2 retainCount]);//1.可以得出深拷贝不会使retainCount+1
    //NSLog(@"ausu1.str retain count is:::%d",[ausu1.str retainCount]);//有注释
    //NSLog(@"ausu2.str retain count is:::%d",[ausu2.str retainCount]);//有注释
    NSLog(@"afer  output ausu.str retain count is:::%d",[str1 retainCount]);
   [ausu1 dealloc];
   [ausu2 dealloc];
    NSLog(@"afer  dealloc retain count is:::%d",[str1 retainCount]);//尽管释放了str1的引用计数,但str1仍然指向那个地方,从未走远
   [pool release];
   return 0;
}
结果:
str1 retain count is:::1
ausu1 retain count is:::1
afer "ausu1.str=str1"retain count is:::2
ausu1 retain count is:::1
ausu2 retain count is:::1
afer output ausu.str retain count is:::4
afer dealloc retain count is:::2///////////////////倒数7、8行未加注释////////////////////
str1 retain count is:::1
ausu1 retain count is:::1
afer "ausu1.str=str1"retain count is:::2
ausu1 retain count is:::1
ausu2 retain count is:::1
ausu1.str retain count is:::5
ausu.str retain countis:::6
afer output ausu.str retain count is:::6
afer dealloc retain count is:::4