简体   繁体   中英

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

I am doing JSON parsing in my App, When I Use responseData = [NSMutableData data]; it crashes on [responseData setLength:0];

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

   [responseData setLength:0];   // CRASH HERE

}

and when I use responseData=[[NSMutableData alloc]init]; my program works fine. I already make property in .h file

@property (strong, nonatomic) NSMutableData* responseData;

and synthesize in .m file

@synthesize responseData;

Question : what is difference between [NSMutableData data] and [[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 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.

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)

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 = [NSMutableData data];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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