Saving data with NSMutableDictionary
I had a method to save a dic to the disk:
+(BOOL) writeApplicationData:(NSDictionary *)data
bwriteFileName:(NSString *)fileName
{
NSLog(@"writeApplicationData");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
NSLog(@"Documents directory not found!");
return NO;
}
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
return ([data writeToFile:appFile atomically:YES]);
}
And I tested it with:
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
NSMutableDictionary *d1 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *d2 = [[NSMutableDictionary alloc] init];
[d1 setObject:@"d11"
forKey:@"d11"];
[d1 setObject:@"d12"
forKey:@"d12"];
[d1 setObject:@"d13"
forKey:@"d13"];
[d2 setObject:@"d21"
forKey:@"d21"];
[d2 setObject:@"d22"
forKey:@"d22"];
[d2 setObject:@"d23"
forKey:@"d23"];
[dic setObject:d1
forKey:@"d1"];
[dic setObject:d2
forKey:@"d2"];
[self writeApplicationData:dic
开发者_开发问答 bwriteFileName:@"testSave"];
And the data is saved correctly.
Then I tried to save d1 with class obj in it:
LevelInfoData *levelInfoData = [[LevelInfoData alloc] init];
[levelInfoDictionary setObject:levelInfoData
forKey:@"test"];
[dic setObject:levelInfoDictionary
forKey:@"LevelInfoDictionary"];
But this time, even no plist file was generated in the disk.
Here is the LevelInfoData class:
@interface LevelInfoData : NSObject {
int levelNum;
}
@property (nonatomic) int levelNum;
@end
@implementation LevelInfoData
@synthesize levelNum;
@synthesize isLevelLocked;
@synthesize isLevelCleared;
@synthesize levelHighScore;
-(id)init
{
if( (self = [super init]) ) {
levelNum = 0;
}
return self;
}
@end
I'm really confused, hope somebody could help me out, thanks.
The contents of the dictionary need to be property list type objects.
From the NSDictionary Class Reference:
This method recursively validates that all the contained objects are property list objects (instances of NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary) before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.
https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html
You may want to try making your custom class a subclass of NSData rather than NSObject.
I'm not sure how attached you are to NSDictionary, but this may be a situation where NSCoder will better serve you.
See nscoder vs nsdictionary when do you use what
More details here:
- NSCoder Class Reference
- Some code snippets
- A tutorial
精彩评论