Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting NSString from char * (Converting C's char-pointer)

I want to show the char * in the UITextField

What I tried:

char *data; char *name=data+6; txtName.text=[[NSString alloc] initWithCString:name encoding:NSUTF8StringEncoding]; 

but I am not getting the correct value.

like image 311
Saraswati Avatar asked May 29 '12 10:05

Saraswati


2 Answers

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 return an object (maybe to Swift), we need to register into nearest @autoreleasepool block (by calling autorelease method to prevent memory-leak, according to ownership-rules), but ARC does 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 the autorelease method (or should if ARC disabled), 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 ARC enabled, these two methods are equivalent (i.e. ARC will auto-call autorelease method; 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.

like image 111
trojanfoe Avatar answered Sep 28 '22 11:09

trojanfoe


What do you expect? You have an uninitalized char*. Then you add 6 to the pointer, which is already undefined behaviour. Then you try to turn a pointer pointing to any old rubbish (and you have no idea where it is pointing) to an NSString*. Nothing good can come from this.

Define a char* pointing to an actual, real C string using ASCII or UTF-8 encoding. Then create an NSString like this:

char* cstring = "Try harder"; NSString* objcstring = @(cstring); 
like image 38
gnasher729 Avatar answered Sep 28 '22 12:09

gnasher729