Search code examples
objective-cplistsaving-data

writing an array onto a file


I am teaching myself Objective C (still) and I am going with the book The Big Nerd Ranch Guide. Read it all through a first time and now I am doing it again but doing the exercises on Xcode as I am reading it. I am getting stuck on the chapter about writing plists. I have copied the code exactly and no warnings. I am sure it's something to do with the path.

Code:

   NSMutableArray *stocks = [[NSMutableArray alloc]init];
    NSMutableDictionary *stock = [NSMutableDictionary dictionary];
    [stock setObject:@"APPL" forKey:@"symbol"];
    [stock setObject:[NSNumber numberWithInt:200] forKey:@"shares"];
    [stocks addObject:stock];

    stock = [NSMutableDictionary dictionary];
    [stock setObject:@"GOOG" forKey:@"symbol"];
    [stock setObject:[NSNumber numberWithInt:160] forKey:@"shares"];
    [stocks addObject:stock];

    [stocks writeToFile:@"/temp/stocks.plist" atomically:YES];

    NSArray *stocklist = [NSArray arrayWithContentsOfFile:@"/temp/stocks.plist"];

    for (NSDictionary *d in stocklist){
    NSLog(@"I have %@ shares of %@", [d objectForKey:@"shares"],[d objectForKey:@"symbol"]);

}

}

It's not printing anything. I can't find the file stock.plist anywhere in my mac. This is the first time I try to save to file, so it may be something simple I am forgetting? Tx


Solution

  • Yes, it is the path causing the issue as /temp will not exist on either an iOS device or a Mac (you don't state what platform in your question):

    [stocks writeToFile:@"/temp/stocks.plist" atomically:YES];
    

    /tmp would probably work, but it's normal to write to the app's own document folder and I am surprised the book does not cover this. Something like this:

    NSString *documentsFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *fullpath = [documentsFolder stringByAppendingPathComponent:@"stocks.plist"];
    [stocks writeToFile:fullpath atomically:YES];
    

    That will work on both iOS and OSX, but where you find it under OSX will depend on if the app is sandboxed or not.