I have a const char * (or const string&), and I would like to append a subsection of it to an NSMutableString.
I figured that I could do
// s: const char *
// start, end: size_t
[anNSMutableString appendString:[[NSString alloc]
initWithBytesNoCopy:s+start
length:end-start
encoding:NSUTF8StringEncoding
freeWhenDone:NO]];
This doesn't work because initWithBytesNoCopy of NSString takes a void * per Apple documentation:
- (instancetype)initWithBytesNoCopy:(void *)bytes
length:(NSUInteger)len
encoding:(NSStringEncoding)encoding
freeWhenDone:(BOOL)freeBuffer;
On the other hand, initWithBytes takes a const void *. Therefore, the above code works if I change it to use initWithBytes.
Question: Why does NSString initWithBytesNoCopy take void * instead of const void *?
Here is my thought process:
- I assume there is a valid reason that
initWithBytesNoCopyis declared to takevoid *instead ofconst void *. - The only valid reason I can think of is that
initWithBytesNoCopymay modifiesbytes, or future operations on the newly createdNSStringmay modify its content.- However, I don't see how/why
initWithBytesNoCopywould modifybytes - I also don't see how operation on
NSStringcan modify its contents becauseNSStringis immutable.
- However, I don't see how/why
- Dead end. What did I get wrong?