Search code examples
xcodenullnsmutablearrayplistnslog

NSMutableArray returning Null from plist


I have an NSMutableArray which contains a list of numbers taken from a textfield.

Im trying to use the tapping of the done button to instigate saving the NSMutableArray in a plist within the NSuserdomain. To check the contents of the plist, im trying to reload them into another NSMUtableArray, and then print the array.

-(NSString *) dataFilePath
{ NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentDirectory = [path objectAtIndex:0]; return     [documentDirectory stringByAppendingPathComponent:@"WeightsList.plist"];
}

- (void)writePlist
{
    [weightsArray writeToFile:[self dataFilePath] atomically:YES];
}

-(void)readPlist
{ 
    NSString *filePath = [self dataFilePath]; 
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
    { 
        NSMutableArray *weightsArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath]; 
    NSLog(@"%@\n",weightsArray); 
    NSLog(@"%@\n", filePath); 
   }
}

The "Done" action below, is what is called when the done button is pressed:

-(IBAction)done { int arrayCount;

id arrayVariable;

arrayCount = [weightsArray count];
[weightsArray addObject:weightInput.text];
arrayVariable = [weightsArray objectAtIndex:arrayCount];
NSLog(@"Weight Entered: %@", arrayVariable);
NSLog(@"%@",weightsArray);
[self writePlist];
[self readPlist];

[self dismissViewControllerAnimated:YES completion:nil];

}

My issue, is that the output is everytime:

2012-05-31 18:35:05.378 WeighMe[780:f803] /Users/jb/Library/Application Support/iPhone     Simulator/5.1/Applications/BE9D2906-50FA-4850-B3A5-47B454601F61/Documents/WeightsList.plist
2012-05-31 18:35:05.829 WeighMe[780:f803] Weight Entered: (null)
2012-05-31 18:35:05.830 WeighMe[780:f803] (null)
2012-05-31 18:35:05.831 WeighMe[780:f803] (
32432
)

Is this an issue with the plist not working correctly, or is it the NSMutableArray which isn't getting the required data.

I've tried stepping through the runtime with the debugger, but tbh i dont really know how to use it properly.

Any help would be awesome! Thanks folks.


Solution

  • You are redeclaring the array in the -(void) readPlist method:

    NSMutableArray *weightsArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath]; 
    

    That line should be:

    weightsArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath];