Write contents of array to a text file

后端 未结 3 990
执笔经年
执笔经年 2021-01-23 18:04

I want to write the contents of an array to a text file in my iPhone application. I can load the array from the text file but i want to allow deleting of content through the arr

相关标签:
3条回答
  • 2021-01-23 18:31

    the approach in other answers works bu the file is written in a XML format. to simply write the contents of the array in a text file , I first Appended all the strings of the array into a large string then write that string into the text file .below is the code i used for that

    NSString *stringToWrite=[[NSString alloc]init];
    
    for (int i=0; i<[stringArray count]; i++)
    
    {
    stringToWrite=[stringToWrite stringByAppendingString:[NSString stringWithFormat:@"%@ ",[stringArray objectAtIndex:i]]];
    
    }
    
    [stringToWrite writeToFile:textFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    

    this will write the contents of the array in plain text format.

    0 讨论(0)
  • 2021-01-23 18:50

    There is method in NSArray to write the array into a file.

    - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
    

    Please check the Apple documentation

    0 讨论(0)
  • 2021-01-23 18:57

    Write the contents of your original array as shown below:

    [firstArray writeToFile:@"/Users/sample/Untitled.txt" atomically:YES];
    

    Whenever you want to retrieve and modify the array, retrieve the contents of the file int an NSMutableArray:

    NSMutableArray *myArr = [NSMutableArray arrayWithContentsOfFile:@"/Users/sample/Untitled.txt"];
    [myArr removeLastObject];  //Any modification you wanna do
    [myArr writeToFile:@"/Users/sample/Untitled.txt" atomically:YES];
    
    0 讨论(0)
提交回复
热议问题