I try to add a custom object class i created to nsuserdefaults array but it always stays empty. The log i’m getting is:
“Note that dictionaries and arrays in property lists must also contain only property values”
my code is:
-(void)addProgramWithName:(NSString *)nameOfProgram andWithArrayOfIntervals:(NSMutableArray *)arrayOfIntervals{
Program *tempProgram = [[Program alloc] init];
tempProgram.nameOfProgram = nameOfProgram;
tempProgram.arrayOfIntervals = arrayOfIntervals;
NSMutableArray *tempArrayOfPrograms = [NSMutableArray arrayWithArray: [[NSUserDefaults standardUserDefaults] arrayForKey: @"arrayOfPrograms"]];
[tempArrayOfPrograms addObject:tempProgram];
[defaults setObject:tempArrayOfPrograms forKey:@"arrayOfPrograms"];
[defaults synchronize];
}
What may the reason be?
The reason for the problem is what the log message says – that for a property list, any object you add to the array (or dictionary) must be a property value (strings, numbers, dates and arrays/dictionaries thereof).
So in your case it seems that you have read in values from the user defaults, and now you want to add some custom objects to the values you have read in.
If you don’t intend to write the amended array back out to the user defaults, there is nothing wrong with this approach (although it strikes me as a somewhat gung-ho approach to data structures).
On the other hand, if you need to write the data back, you should only store property values in the array. For more complex objects, that can be accomplished by encoding it in a dictionary object with keys and values.
Depending on your needs, Core Data might be more suited for your data, though.