gpt4 book ai didi

cocoa - 字符串到字符串 EXC_BAD_ACCESS 为什么?

转载 作者:行者123 更新时间:2023-12-03 18:00:46 25 4
gpt4 key购买 nike

我错过了什么?

NSString * configPath = nil;
-(IBAction)setPlistPathAndWriteData:(id)sender{
NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setDirectory:@"/Volumes/"];
[panel setNameFieldStringValue:@"config.plist"];
[panel setRequiredFileType:@"plist"];
NSInteger ret = [panel runModal];

if ( ret == NSFileHandlingPanelOKButton ) {
NSString *filePath= [[panel URL] path];
// with this works fine
//configPath = [NSString stringWithFormat:@"/Volumes/Macintosh HD/config.plist"];
// with this EXC BAD ACCESS
configPath = [NSString stringWithFormat:@"%@", filePath];
[self writeData];
}
}

-(void)writeData {
SET_TEMP_PLIST
NSTask *task = [[NSTask alloc] init];
NSPipe *pipe = [[NSPipe alloc] init];
NSFileHandle *writeHandle = [pipe fileHandleForWriting];
NSData *configData = [NSPropertyListSerialization dataFromPropertyList:tmpPlist format:
NSPropertyListXMLFormat_v1_0 errorDescription:nil];
[task setLaunchPath:@"/usr/libexec/authopen"];
////////////////////////////////////////////////////////EXC_BAD_ACCESS HERE////////
[task setArguments:[NSArray arrayWithObjects:@"-c", @"-w", configPath, nil]];
[task setStandardInput:pipe];
[writeHandle writeData:configData];
[task launch];
close([writeHandle fileDescriptor]);
[task waitUntilExit];
[task release];
}

编辑

嗯...使用此代码可以正常工作:

NSString *filePath= [[[panel URL] path] retain];
const char * cString = [filePath UTF8String];
configPath = [[NSString stringWithUTF8String:cString] retain];

但这不是完美的方法..想法

最佳答案

您的应用程序崩溃可能是因为 configPathnil,稍后在 writeData 中您尝试使用 nil< 初始化一个新数组 作为第三个对象:

[NSArray arrayWithObjects:@"-c", @"-w", configPath, nil]
// ^^^ this is nil

我建议您复制 path 返回的字符串:

if(ret == NSFileHandlingPanelOKButton ) {
// you become the owner of the string,
// don't forget to release configPath later
configPath = [[[panel URL] path] copy];
[self writeData];
}

这可能会毫无问题地运行。

关于cocoa - 字符串到字符串 EXC_BAD_ACCESS 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6855100/

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