Re: Unclear on -initWithBytesNoCopy:
Re: Unclear on -initWithBytesNoCopy:
- Subject: Re: Unclear on -initWithBytesNoCopy:
- From: Jens Alfke <email@hidden>
- Date: Sat, 03 Mar 2012 12:24:51 -0800
On Mar 3, 2012, at 11:28 AM, Dave Keck wrote:
> The buffer needs to remain intact until the NSString/NSData object is deallocated.
True; but a strict interpretation of this is that the buffer can _never_ be destroyed, because you can never predict with 100% accuracy when an object is going to be deallocated. (as discussed in all those “why -retainCount is useless for debugging” threads.)
In practice I’ve tended to be more pragmatic about this, avoiding using such a string in a situation where I know something else is going to retain it (like setting it as a property value on an object.) In this case it was absolutely not intuitive to me that creating a substring of the string would cause the original string to be retained; that’s a tricky optimization practiced by this particular implementation and I shouldn’t have to know about it.
> I suppose this scenario reinforces that if your method is passed a
> NSString/NSData object and you need to keep it around longer than the
> current stack frame, then you must copy the string/data object.
Yes. I try to follow that, myself (and for arrays/dictionaries/sets as well). It’s usually not any more expensive, since an immutable Foundation object responds to -copy by just calling -retain.
There’s a parallel with mutable strings: If I create a mutable string and do stuff with it, when am I subsequently allowed to modify the contents without breaking things? We could rewrite my example this way:
NSMutableString* str = [NSMutableString stringWithString: @“I HAZ A STRING”];
NSString* substr = [str substringWithRange: NSMakeRange(2, 3)];
[str setString: @“************”];
NSLog(@“substr = %@“, substr];
In this case it’s pretty obvious that substr should still be “HAZ”, not “***”. -substringWithRange: knows that it can’t create a pointer into the receiver’s buffer because its contents might change later. I’d argue that the same is true of the original example, that the string should know that the caller might release it and then invalidate the buffer.
(BTW: Someone on the GNUstep mailing list just looked into Apple's CF source code and confirmed that CFStringCreateSubstring always copies the bytes.)
—Jens
_______________________________________________
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