在iphone上逐行写入数据

在iphone上逐行写入数据,iphone,Iphone,我可以在iphone上写入文本文件..但每次写入之前的值时,都会被擦除,是否有任何方法可以将写入的数据分隔为\n 这是我的密码 NSString *cc=@"1"; [cc writeToFile:storePath atomically:YES]; NSString *myText1 = [NSString stringWithContentsOfFile:storePath]; NSLog(@"text is %@",myText1); 这给了我1现在我想添加

我可以在iphone上写入文本文件..但每次写入之前的值时,都会被擦除,是否有任何方法可以将写入的数据分隔为\n

这是我的密码

NSString *cc=@"1";

    [cc writeToFile:storePath atomically:YES];

    NSString *myText1 = [NSString stringWithContentsOfFile:storePath];

    NSLog(@"text is %@",myText1);

这给了我1现在我想添加2,比如1,然后使用
NSFileHandle
方法
seektoEndofile
和调用
writeData

NSFileHandle *aFileHandle;
NSString *aFile;

aFile = [NSString stringWithString:@"Your File Path"]; //setting the file to write to

aFileHandle = [NSFileHandle fileHandleForWritingAtPath:aFile]; //telling aFilehandle what file write to
[aFileHandle truncateFileAtOffset:[aFileHandle seekToEndOfFile]]; //setting aFileHandle to write at the end of the file

[aFileHandle writeData:[toBeWritten dataUsingEncoding:nil]]; //actually write the data

我不完全理解这个问题,但您可以在每次保存文本时尝试,首先读取文件中已有的文本,然后使用stringByAppendingString

NSString *begRainbow = @"Red orange yellow green";
NSString *fullRainbow = [begRainbow stringByAppendingString:@" blue purple"];

将fullRainbow的值保留为“红橙色黄绿色蓝紫色”。

在NSMutableArray中添加所有包含的文件,然后在每次加载项数组中写入时写入此

以下是一个NSString类别方法,该方法将使用指定的编码(通常为NSUTF8StringEncoding)将接收器附加到指定路径


这是非常低效的,尤其是对于较大的文件,在[aFileHandle writeData:[myText1 DataUsingEncode:nil]]上获取错误;其中,mytext1是要附加到现有文件
dataUsingEncoding:
上的NSString,实际上不接受对象。尝试使用
dataUsingEncoding:NSUTF8StringEncoding
,它将以UTF-8的形式编写文本(现在几乎被普遍理解)。
- (BOOL) appendToFile:(NSString *)path encoding:(NSStringEncoding)enc;
{
    BOOL result = YES;
    NSFileHandle* fh = [NSFileHandle fileHandleForWritingAtPath:path];
    if ( !fh ) {
        [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
        fh = [NSFileHandle fileHandleForWritingAtPath:path];
    }
    if ( !fh ) return NO;
    @try {
        [fh seekToEndOfFile];
        [fh writeData:[self dataUsingEncoding:enc]];
    }
    @catch (NSException * e) {
        result = NO;
    }
    [fh closeFile];
    return result;
}