2011-10-13 69 views
0

分隔的文件,我发现这个片段在网上写,然后将数据追加到一个文本文件:创建标签在Objective-C

- (void)appendText:(NSString *)text toFile:(NSString *)filePath { 

    // NSFileHandle won't create the file for us, so we need to check to make sure it exists 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    if (![fileManager fileExistsAtPath:filePath]) { 

     // the file doesn't exist yet, so we can just write out the text using the 
     // NSString convenience method 

     NSError *error = noErr; 
     BOOL success = [text writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error]; 
     if (!success) { 
      // handle the error 
      NSLog(@"%@", error); 
     } 

    } 
    else { 

     // the file already exists, so we should append the text to the end 

     // get a handle to the file 
     NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath]; 

     // move to the end of the file 
     [fileHandle seekToEndOfFile]; 

     // convert the string to an NSData object 
     NSData *textData = [text dataUsingEncoding:NSUTF8StringEncoding]; 

     // write the data to the end of the file 
     [fileHandle writeData:textData]; 

     // clean up 
     [fileHandle closeFile]; 
    } 
} 

这对我来说很有意义。我有一个有3个属性的类,NSString,NSInteger和NSString。当我尝试使用这种方法时,我这样做:

for (MyObject *ref in array) { 
    NSString *stringToFile = [NSString stringWithFormat:@"%@\t%i\t%@", ref.ChrID, ref.Position, ref.Sequence]; 
    [self appendText:stringToFile toFile:filePath]; 
} 

它看起来不太正确。我的数据如下所示:

NSString *tab* NSInteger *single space* NSStringNSString *tab* NSInteger newline 
NSStringNSString *tab* NSInteger newline 
NSStringNSString *tab* NSInteger newline 
NSStringNSString *tab* NSInteger newline 
NSStringNSString *tab* NSInteger newline 
NSStringNSString *tab* NSInteger newline 
NSStringNSString *tab* NSInteger newline 
NSStringNSString *tab* NSInteger newline 
... 

我不确定发生了什么事情来使它看起来像这样。当我NSLog数据,它看起来很好。但是,第一行的东西会搞砸,然后一切都会消失。有什么想法吗?谢谢。

+2

首先,在格式化字符串的末尾加上换行符(\ n)。您可能需要一对\ r \ n。 – Flyingdiver

+0

另外,MyObject的声明是什么? – Flyingdiver

+1

@Flyingdiver据我所知,在Windows上需要'\ r \ n'对,但不是任何基于Unix的文件系统(包括OS X和iOS),尽管大多数Unix系统都能容忍它们。 – jlehr

回答

1

没有与方法appendText几个问题:

  • 如果文件不存在,第一行写有NSString的writeToFile方法没有\ n

  • 以下行被写入与NSData writeData方法

  • 它是非常低效的使用filemanager检查存在,获取文件句柄,寻求EOF,然后只写一个李ne,省略了关闭。并为每一条下面的行重复这一点。

因此,更好地做到这一点是这样的:

  • 获得书面文件句柄,它将被创建,如果它不存在尚未

  • 寻求EOF

  • 做你的循环与每行writeData的数据

  • cl其他文件