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数据,它看起来很好。但是,第一行的东西会搞砸,然后一切都会消失。有什么想法吗?谢谢。
首先,在格式化字符串的末尾加上换行符(\ n)。您可能需要一对\ r \ n。 – Flyingdiver
另外,MyObject的声明是什么? – Flyingdiver
@Flyingdiver据我所知,在Windows上需要'\ r \ n'对,但不是任何基于Unix的文件系统(包括OS X和iOS),尽管大多数Unix系统都能容忍它们。 – jlehr