开发者

Objective-C file i/o error

开发者 https://www.devze.com 2023-03-18 16:39 出处:网络
- (IBAction)sendMessage:(id)sender { NSString* conversationFile = [@\"~/\" stringByAppendingPathComponent:@\"conversation.txt\"];
- (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];

}

The above code presents the following error

2011-07-07 21:38:08.703 iMessages[86493:903] -[NSPlaceholderString stringWithContentsOfFile:encoding:error:]: unrecognized selector sent to instance 0x100111690

2011-07-07 21:38:08.704 iMessages[86493:903] -[NSPlaceholderString stringWithContentsOfFile:encoding:error:]: unrecognized selector sent to instance 0x100111690


stringWithContentsOfFile:encoding:error: is a class method of NSString, not an instance method, so you don't need to (shouldn't) alloc it first.

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


Use initWithContentsOfFile in place of stringWithContentsOfFile or remove the alloc call. So have:

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

or

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

精彩评论

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