我想在 UITextField
中显示 char *
我尝试过的:
char *data;
char *name=data+6;
txtName.text=[[NSString alloc] initWithCString:name encoding:NSUTF8StringEncoding];
但我没有得到正确的值。
最佳答案
要从 const char *
创建一个 NSString
,只需使用这些方法:
返回一个 autorelease
d 对象:
/**
* 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 toSwift
), we need to register into nearest@autoreleasepool
block (by callingautorelease
method to prevent memory-leak, according to ownership-rules), butARC
does that automatically for us.
但即使禁用了 ARC
,我们也不会被迫手动调用 autorelease
,例如:
return [[NSString stringWithUTF8String: name] autorelease];
Generally, convenience factory methods (like
stringWithUTF8String:
), already call theautorelease
method (or should ifARC
disabled), because the class simply does not intend to own the instance.
创建一个保留
对象:
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-callautorelease
method; always registering to nearest@autoreleasepool
).
如果您没有获得正确的值,则说明数据有问题。添加一些 NSLog
调用以查看字符串包含的内容。
关于iphone - 从 char * 获取 NSString(转换 C 的字符指针),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10797350/