简体   繁体   English

[NSMutableData数据]和[[NSMutableData alloc] init]之间的区别

[英]Difference between [NSMutableData data] and [[NSMutableData alloc]init]

I am doing JSON parsing in my App, When I Use responseData = [NSMutableData data]; 当我使用responseData = [NSMutableData data]时,我正在我的App中进行JSON解析 it crashes on [responseData setLength:0]; 它在[responseData setLength:0]上崩溃;

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

   [responseData setLength:0];   // CRASH HERE

}

and when I use responseData=[[NSMutableData alloc]init]; 当我使用responseData = [[[NSMutableData alloc] init]; my program works fine. 我的程序运行正常。 I already make property in .h file 我已经在.h文件中设置了属性

@property (strong, nonatomic) NSMutableData* responseData;

and synthesize in .m file 并在.m文件中合成

@synthesize responseData;

Question : what is difference between [NSMutableData data] and [[NSMutableData alloc]init]; 问题: [NSMutableData数据][[NSMutableData alloc] init]有什么区别

thanks 谢谢

[NSMutableData data]返回一个自动释放的对象,而[[NSMutableData alloc] init]返回一个保留的对象。

[NSMutableData data] returns an autorelease object, ie it will be added to the auto-release pool and at the end of a frame a release will be called on that object and if reference count becomes 0 it will be cleaned from memory. [NSMutableData data]返回一个autorelease对象,即,它将被添加到自动释放池中,并且在帧的结尾,将对该对象调用释放,并且如果引用计数变为0,它将从内存中清除。

[[NSMutableData alloc] init] returns an object with reference count 1, and here you need to remove it from memory explicitly by calling release , once you are done. [[NSMutableData alloc] init]返回一个引用计数为1的对象,完成后,您需要通过调用release显式地将其从内存中删除。

So solution for your problem is: 因此,解决您的问题的方法是:

// 1. retain explicitly
responseData = [[NSMutableData data] retain];

// 2. or else define
@property (retain, nonatomic)

The second option will retain the object. 第二个选项将保留对象。 So even if release is called on autorelease pool it wont be flushed as its retained (reference count wont be zero) 因此,即使在autorelease池上调用release它也不会因为保留而被刷新(引用计数不会为零)

As you are using self.responseData , its reference count increases by 1, so even if you assign autorelease object its gets retained due to declared property: 当您使用self.responseData ,其引用计数将增加1,因此,即使您分配了autorelease对象,它也会由于声明的属性而被保留:

self.responseData = [NSMutableData data];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM