To create an NSString from a const char *, simply use these methods:
Returns an autoreleased object:
/**
* Should be wrapped in `@autoreleasepool {...}`,
* somewhere not far in call-stack
* (as closer it's, the lower our memory usage).
*/
NSString *stringFromChar(const char *input) {
return [NSString stringWithUTF8String: input];
}
Whenever we
returnan object (maybe toSwift), we need to register into nearest@autoreleasepoolblock (by callingautoreleasemethod to prevent memory-leak, according to ownership-rules), butARCdoes that automatically for us.
But even with ARC disabled, we are NOT forced to call autorelease manually, like:
return [[NSString stringWithUTF8String: name] autorelease];
Generally, convenience factory methods (like
stringWithUTF8String:), already call theautoreleasemethod (or should ifARCdisabled), because the class simply does not intend to own the instance.
Creates a retained object:
NSString *result = [[NSString alloc] initWithUTF8String: name];
// ... Do something with resulted object.
// NOTE: calling below is not required
// (If ARC enabled, and should cause compile error).
[result release];
Update 2021 about difference; With
ARCenabled, these two methods are equivalent (i.e.ARCwill auto-callautoreleasemethod; always registering to nearest@autoreleasepool).
Reference.
If you are not getting the correct value, then something is wrong with the data. Add a few NSLog calls to see what the strings contain.