0

我正在尝试将我写入控制台的内容镜像到文本文件。这是我编写的代码,但它没有创建 txt 文件。任何帮助是极大的赞赏:

-(NSString *) display
{
    NSLog (@" \n ");
    NSLog (@"|========== Contents of: %@ =============|", listName);
    NSLog (@"|__________________________________________________|");
    NSLog (@"|    | Song Title |    |         | Artist |        |");
    NSLog (@"|    ==============    |         ==========        |");
    NSLog (@"|~~~~~~~~~~~~~~~~~~~~~~|~~~~~~~~~~~~~~~~~~~~~~~~~~~|");

    for ( SongRecord *theRecord in list )
        NSLog (@"|  %-20s|  %-24s |", [theRecord.songname UTF8String],
           [theRecord.artist UTF8String]);

    NSLog (@"====================================================");

    return listing;
}


-(void) saveToFile
{
     NSString* fileName = @"Mysongs.txt";
     NSString* fullPath = [path stringByAppendingPathComponent:fileName];



     [[self display] writeToFile:fullPath atomically:YES encoding:NSUnicodeStringEncoding    error:nil];

     NSLog (@"The file has been written");

}
4

2 回答 2

6

修改-display,以便它构建一个字符串,您可以实际返回以在-saveToFile. 同时,您可以根据需要将其发送到控制台:

- (NSString *)display
{
    NSMutableString *listing = [NSMutableString string];

    [listing appendString:@"\n"];
    [listing appendFormat:@"|========== Contents of: %@ =============|\n", listName];
    [listing appendString:@"|__________________________________________________|\n"];
    [listing appendString:@"|    | Song Title |    |         | Artist |        |\n"];
    [listing appendString:@"|    ==============    |         ==========        |\n"];
    [listing appendString:@"|~~~~~~~~~~~~~~~~~~~~~~|~~~~~~~~~~~~~~~~~~~~~~~~~~~|\n"];

    for (SongRecord *theRecord in list)
    {
        [listing appendFormat:@"|  %-20s|  %-24s |\n", [theRecord.songname UTF8String], [theRecord.artist UTF8String]];
    }

    [listing appendString:@"====================================================\n"];

    NSLog(@"%@", listing);

    // Do this to return an immutable string, as your method signature says it will.
    return [NSString stringWithString:listing];
}
于 2012-12-16T06:03:20.537 回答
0

感谢所有的帮助。它最终成为我如何定义我的路径的问题。我改为 NSHomeDirectory ,它就像一个魅力。再次感谢,尤其是@trudyscousin。

于 2012-12-16T19:50:30.773 回答