Search code examples
arraysnsarraywritetofile

Objective-C - How to write an array to a file?


I have a text file that I can scan (NSScanner) and tag. The results are stored in an array. The structure is two strings, one for english and one for greek.

I want to write an output file that maintains the array structure. I presume I can create a plist file for this purpose.

However, I'm stuck and need help to create this file.

I have a test whether the file was created, but I get this result:

outgoingWords.count: 442
2014-08-12 17:54:17.369 MyScanner[97350:2681695] *** Assertion failure in -[ViewController checkArray], /Users/david/Desktop/Word Scanning/MyScanner/MyScanner/ViewController.m:98
2014-08-12 17:54:17.373 MyScanner[97350:2681695] Failed to set (contentViewController) user defined inspected property on (NSWindow): writeToFile failed

The code I'm using so far is as follows:

-(void)checkArray {

    //do stuff to verify the array       

    long i = outgoingWords.count;
    NSString *tempString = [NSString stringWithFormat:@"%li", i];
    NSLog(@"outgoingWords.count: %@", tempString); //442

    NSArray *tempArray2 = [outgoingWords copy];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"/Users/David/Desktop/alfa2" ofType:@"plist"];

    BOOL success = [tempArray2 writeToFile:path atomically:YES];
    NSAssert(success, @"writeToFile failed");
  }

Could someone either identify what I'm missing, or point me to an existing answer I can use (I've looked)..

Many thanks..

edit. I've also tried the approach in this SO question. But get the same result.

 NSString *path = [[NSBundle mainBundle] pathForResource:@"/Users/David/Desktop/alfa2" ofType:@"plist"];

    NSString *error;
    NSData *data = [NSPropertyListSerialization dataFromPropertyList:tempArray2 format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error];

    BOOL success = [NSKeyedArchiver archiveRootObject:data toFile:path];
    NSAssert(success, @"archiveRootObject failed");

Solution

  • Problem is that you are writing to the bundle, which is not allowed. You should write to a path in your document or other directory, for example:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    filePath = [documentsDirectory stringByAppendingPathComponent:@"FileName.xxx"];
    [data writeToFile:filePath atomically:NO];