objective-c - 将 const char* 转换为 NSString * 并转换回来 - _NSAutoreleaseNoPool()

标签 objective-c xcode

我正在尝试将 const char* 转换为 NSString *,然后再将其转换回来。它有效,但我得到:

__NSAutoreleaseNoPool(): Object 0x100550a40 of class NSCFArray autoreleased with no pool in place - just leaking
__NSAutoreleaseNoPool(): Object 0x100551730 of class NSCFString autoreleased with no pool in place - just leaking
__NSAutoreleaseNoPool(): Object 0x100551f10 of class NSCFData autoreleased with no pool in place - just leaking

代码是:

const char* convert = "hello remove this: *";

NSString *input = [[NSString alloc] initWithUTF8String:convert];// convert 

//remove * FROM THE STRING          
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"*"]; 

// REPLACE * WITH NOTHING                   
input = [[input componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];

// CONVERT BACK         
const char *converted_back = [input UTF8String]; 

我迷路了,请帮帮我。

最佳答案

如果您在后台线程中执行此操作,请添加一个 NSAutoReleasePool。

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
const char* convert = "hello remove this: *";
NSString *input = [[[NSString alloc] initWithUTF8String:convert] autorelease];// convert 
//remove * FROM THE STRING          
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"*"]; 
// REPLACE * WITH NOTHING                   
input = [[input componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
// CONVERT BACK         
const char *converted_back = [input UTF8String]; 
[pool drain];

此外,您需要在完成后释放 input,或者使其自动释放。

关于objective-c - 将 const char* 转换为 NSString * 并转换回来 - _NSAutoreleaseNoPool(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10284011/

相关文章:

ios - 为什么 UILabel 内存泄漏?

ios - UITextfield 的文本在填充后不会向左移动 - 因为我一直在输入

objective-c - 动态列出类的IBOutlets

ios - SwiftUI 在没有按钮的情况下询问通知权限

xcode - 音乐即将在iPhone应用程序中播放时出错

ios - 从 Storyboard 而不是 nib 加载自定义 TableViewCell

ios - 如何在 ScrollView 内滚动时更改多个 UILabel 文本颜色 Objective-c iOS

objective-c - 从 UIWebView 移除阴影

objective-c - 我如何扩展 NSArray?

Xcode:iOS Simulator Dev Menu 无法打开