Iphone [NSMutableData]和[[NSMutableData alloc]init]之间的差异
当我使用responseData=[NSMutableData]时,我正在我的应用程序中进行JSON解析;它在[responseData setLength:0]上崩溃Iphone [NSMutableData]和[[NSMutableData alloc]init]之间的差异,iphone,ios,Iphone,Ios,当我使用responseData=[NSMutableData]时,我正在我的应用程序中进行JSON解析;它在[responseData setLength:0]上崩溃 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [responseData setLength:0]; // CRASH HERE } 当我使用responseData=
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0]; // CRASH HERE
}
当我使用responseData=[[NSMutableData alloc]init]时;我的程序运行良好。我已经在.h文件中创建了属性
@property (strong, nonatomic) NSMutableData* responseData;
并在.m文件中进行合成
@synthesize responseData;
问题:[NSMutableData]和[[NSMutableData alloc]init]之间有什么区别
谢谢[NSMutableData]返回自动删除的对象,而[[NSMutableData alloc]init]返回保留的对象 [NSMutableData]返回一个自动释放对象,即它将被添加到自动释放池中,在帧结束时,将对该对象调用一个释放,如果引用计数变为0,它将从内存中清除
[[NSMutableData alloc]init]返回一个引用计数为1的对象,在这里,一旦完成,您需要通过调用release显式地将其从内存中删除
因此,您的问题的解决方案是:
// 1. retain explicitly
responseData = [[NSMutableData data] retain];
// 2. or else define
@property (retain, nonatomic)
第二个选项将保留该对象。所以,即使在自动释放池上调用release,也不会刷新它,因为它的保留引用计数不会为零
当您使用self.responseData时,其引用计数增加1,因此即使您指定autorelease对象,其引用计数也会由于声明的属性而保留:
self.responseData = [NSMutableData data];
尝试self.responseData=[NSMutableData];