سؤال

I'm trying to use the - (void)getCharacters:(unichar *)buffer range:(NSRange)aRange method of a NSString object but I have an issue with the first parameter. The number of characters in this NSString is not fixed so I need to allocate my buffer dynamicly (the size of the buffer must be something like [my_string length] * sizeof(UniChar)).

I'm new in objective C and don't know how to do that. Can I use malloc(ARC is enabled) like in C program ?

هل كانت مفيدة؟

المحلول

Yes, you can malloc() a buffer of the appropriate size. You have to free() the buffer when it is no longer used, because ARC does not manage malloced memory.

Alternatively, create an NSData object with the UTF-16 encoding:

NSString *string = @"H€llö Wörld";
NSData *data = [string dataUsingEncoding:NSUTF16LittleEndianStringEncoding];
const unichar *charsPtr = [data bytes];

charsPtr is valid as long as data exists, i.e. as long as you keep a strong reference to it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top