gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 07:53:36 25 4
gpt4 key购买 nike

我想在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com