开发者

String to string EXC_BAD_ACCESS why?

开发者 https://www.devze.com 2023-03-23 06:12 出处:网络
whats I missed? NSString * configPath = nil; -(IBAction)setPlistPathAndWriteData:(id)sender{ NSOpenPanel *panel = [NSOpenPanel openPanel];

whats I missed?

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

EDIT

well... works fine with this code:

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

but this is not perfect method.. thought


Your app crashes likely because configPath is nil, and later in writeData you try to initialize a new array with nil as the third object :

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

I suggest you copy the string returned by 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];
}

This may run without any problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号