Re: Creating NSStrings without copying memory
Re: Creating NSStrings without copying memory
- Subject: Re: Creating NSStrings without copying memory
- From: Ken Thomases <email@hidden>
- Date: Tue, 2 May 2017 20:49:45 -0500
On May 2, 2017, at 3:11 PM, Jens Alfke <email@hidden> wrote:
>
> I’ve got a heap block containing many UTF-8 strings, and I’m looking for the cheapest way to create NSString objects from them, i.e. without copying all the characters.
>
> -initWithBytesNoCopy:length:freeWhenDone: would be perfect, except that the string bytes are not an individual malloc block (so I can’t use freeWhenDone:YES), and I shouldn’t leave the big heap block in memory longer than necessary (so I can’t use freeWhenDone:NO.)
>
> NSData has -initWithBytesNoCopy:length:deallocator:, which is exactly what I want: the callback block tells me when the object doesn’t need the original bytes anymore, so I can reference-count that heap block and free it when there are no clients left. But NSString doesn’t have this :(
>
> If I created an NSData from the bytes this way, and then used that object to initialize an NSString, would I get what I want? Or would the NSString initializer just copy the bytes from the NSData without retaining it? Has anyone experimented with this?
I would try creating an NSData object for the whole block using +dataWithBytesNoCopy:length:freeWhenDone:, creating sub-data objects for each string using -subdataWithRange:, then creating strings from those using -initWithData:encoding:. The sub-data objects should just retain the original data object and reference a range within it. The strings will probably retain the sub-data objects. (Well, I'm sure they'll use -copy on them to make sure they have an immutable object, but that will just do a retain.)
Regards,
Ken
_______________________________________________
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