简体   繁体   中英

Need help with iphone sdk: not correctly saving .plist to documents directory

I've been spending way too long trying to figure out what is going wrong, so I hope someone her can help me out.

My Code:

- (IBAction)fedDog {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"dogsFedDays.plist"];  
    NSMutableArray *dogsFedSave = [[NSMutableArray alloc] arrayWithCapacity: 48]; 
    for (int i = 0; i < 48; i++) { 
        NSDictionary *myDict = [[NSDictionary alloc] initWithObjectsAndKeys: 
                                date[i], @"string",
                                fed[i], @"Yes",
                                nil]; 
        [dogsFedSave addObject:myDict]; 
        [myDict release]; 
    } 
    if (![dogsFedSave writeToFile:path atomically:YES]) 
        NSLog(@"not successful in completing this task"); 
}

I've connected the action to a button, but when the button is pressed, the simulator freezes, and no file appears in the Documents directory.

For starters, your action method should take a single argument as opposed to none. Beyond that, have you run it in the debugger?

It's possible that the simulator freezes because of an unhandled exception. Check the debug console while your app is running. The most probable reason your application hangs is that the button pressed may be calling fedDog: method. Try changing your method signature to this one:

- (IBAction)fedDog:(id)sender {
    // your code
}

You are trying to send arrayWithCapacity to an instance of NSMutableArray, but it is actually declared as

+ (id)arrayWithCapacity:(NSUInteger)numItems

and hence a class method.

So either use

NSMutableArray *dogsFedSave = [[NSMutableArray alloc] initWithCapacity:48];

or

NSMutableArray *dogsFedSave = [NSMutableArray arrayWithCapacity:48];

The latter would be better, since it results in an autoreleased object (and you forgot to release dogsFedSave anyway…)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM