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

时间:2011-07-28 06:54:29

标签: cocoa nsstring exc-bad-access

我错过了什么?

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];

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

1 个答案:

答案 0 :(得分:1)

您的应用可能崩溃,因为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];
}

这可能没有任何问题。