Objective-C文件i / o错误

时间:2011-07-08 01:39:28

标签: objective-c nsstring io filehandle

- (IBAction)sendMessage:(id)sender
{
    NSString* conversationFile = [@"~/" stringByAppendingPathComponent:@"conversation.txt"];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:conversationFile];

    if (fileExists == FALSE)
    {
        [self doShellScript:@"do shell script \"cd ~/; touch conversation.txt\""];
    }

    NSString *conversationContent = [[NSString alloc] stringWithContentsOfFile:@"~/conversation.txt" encoding:NSUTF8StringEncoding error:NULL];
    NSString *myMessage = [[messageBox stringValue]copy];

    NSString *combinedContent = [NSString stringWithFormat:@"%@ \r\n %@", conversationContent, myMessage];
    [[[myConversationBox textStorage] mutableString] setString: combinedContent];
    [combinedContent writeToFile:@"~/conversation.txt" atomically:YES encoding:NSUTF8StringEncoding error:NULL];

}

以上代码显示以下错误

  

2011-07-07 21:38:08.703   iMessage讯息[86493:903]    - [NSPlaceholderString stringWithContentsOfFile:encoding:error:]:   无法识别的选择器发送到实例   0x100111690

     

2011-07-07 21:38:08.704   iMessage讯息[86493:903]    - [NSPlaceholderString stringWithContentsOfFile:encoding:error:]:   无法识别的选择器发送到实例   0x100111690

2 个答案:

答案 0 :(得分:2)

stringWithContentsOfFile:encoding:error:NSString的类方法,而不是实例方法,因此您不需要(不应该)首先分配它。

NSString *conversationContent = [NSString stringWithContentsOfFile:@"~/conversation.txt" encoding:NSUTF8StringEncoding error:NULL];

答案 1 :(得分:1)

使用initWithContentsOfFile代替stringWithContentsOfFile或删除alloc来电。所以:

NSString *conversationContent = [[NSString alloc] initWithContentsOfFile:@"~/conversation.txt" encoding:NSUTF8StringEncoding error:NULL];

NSString *conversationContent = [NSString stringWithContentsOfFile:@"~/conversation.txt" encoding:NSUTF8StringEncoding error:NULL];