iphone - 从 char * 获取 NSString(转换 C 的字符指针)

标签 iphone objective-c ios

我想在 UITextField 中显示 char *

我尝试过的:

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

但我没有得到正确的值。

最佳答案

要从 const char * 创建一个 NSString,只需使用这些方法:

返回一个 autoreleased 对象:

/**
 * 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.

但即使禁用了 ARC,我们也不会被迫手动调用 autorelease,例如:

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.

创建一个保留对象:

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 .

如果您没有获得正确的值,则说明数据有问题。添加一些 NSLog 调用以查看字符串包含的内容。

关于iphone - 从 char * 获取 NSString(转换 C 的字符指针),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10797350/

相关文章:

iphone - 我想忽略证书验证,在哪里以及如何使用 XMLRPC Web 服务来做到这一点?

iphone - 如何捕获 iPhone 应用程序中的其他应用程序事件?

iphone - 如何将 ipa 文件添加到 windows 机器上的 itunes 中?

ios - 我们如何在 UIAlertView 中显示表格 View

ios - 使用自定义字体时某些特殊的越南字符大小错误

iphone - NSMutableArray 没有正确添加对象?

objective-c - 将 char[] 写入 NSOutputStream 并从 NSInputStream 读取

ios - 如何获得可用 NSFont 系列的列表?

ios - 在 iOS7 的 View 之上添加 UISearchBar 修复?

c# - 图像不保留缩放比例和偏移