Re: mutableBytes Creates Autoreleased Objects
Re: mutableBytes Creates Autoreleased Objects
- Subject: Re: mutableBytes Creates Autoreleased Objects
- From: Charles Srstka <email@hidden>
- Date: Sat, 12 May 2012 12:27:19 -0500
On May 12, 2012, at 12:17 PM, Ken Thomases wrote:
> That's not necessarily so. And/or requesting the mutableBytes may do the equivalent of retain+autorelease on the NSMutableData.
>
> Consider an inexact analog. The -[NSString UTF8String] method seems to create an autoreleased NSData (or similar object) to hold the UTF-8-encoded C string that it returns. It's not returning the NSData object, obviously, it's just using the autoreleased lifetime to manage the lifetime of the C string.
>
> Anyway, NSMutableData *could* be doing something similar. I don't know if it is or isn't. I believe that Andreas is saying that his testing shows that it is. If it is, Apple may have done this specifically to avoid a problem with internal pointers in ARC.
It looks like that’s indeed what it’s doing. I put a category on NSData to swizzle out its dealloc to something that would log that it was getting dealloced, and then ran a few test cases. Here’s where the data object got dealloced each time:
int main(int argc, const char * argv[]) {
@autoreleasepool {
const char *bytes = "abcd";
{
NSMutableData *data = [[NSMutableData alloc] initWithBytes:bytes length:4];
NSLog(@"leaving block");
} // data gets dealloced here
NSLog(@"left block");
}
return 0;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
const char *bytes = "abcd";
char *mutableBytes;
{
NSMutableData *data = [[NSMutableData alloc] initWithBytes:bytes length:4];
mutableBytes = [data mutableBytes];
NSLog(@"leaving block");
}
NSLog(@"left block");
} // data gets dealloced here
return 0;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
const char *bytes = "abcd";
char *mutableBytes;
@autoreleasepool {
NSMutableData *data = [[NSMutableData alloc] initWithBytes:bytes length:4];
mutableBytes = [data mutableBytes];
NSLog(@"leaving autoreleasepool block");
} // data gets dealloced here
NSLog(@"left autoreleasepool block");
}
return 0;
}
Charles
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden