write data line by line on iphone

后端 未结 4 1333
抹茶落季
抹茶落季 2020-12-11 08:37

i can write to a text file on iphone..but each time i write my previous value is erased, is there any way to keep writing data separated by \\n??

this is my code

相关标签:
4条回答
  • 2020-12-11 09:09

    Use NSFileHandle method seekToEndOfFile and the call to 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
    
    0 讨论(0)
  • 2020-12-11 09:18

    I dont fully understand the question, but you could try each time you are saving the text, first read the text already in the file then use the stringByAppendingString.For example, the code

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

    Leaves fullRainbow with a value of "Red orange yellow green blue purple".

    0 讨论(0)
  • 2020-12-11 09:23

    Add All file contain in an NSMutableArray then Write Each time Add in array An Write this

    0 讨论(0)
  • 2020-12-11 09:26

    Here is an NSString category method that will append the receiver to the specified path with the specified encoding (normally NSUTF8StringEncoding).

    - (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;
    }
    
    0 讨论(0)
提交回复
热议问题