0

i want to save a mutable dictionary to file. the dictionary has several mutable arrays that contain custom object that I implemented. I've implemented the NSCoder protocol in my class but for some reason the property values in those objects get set to nil when the dictionary is read from the file. this is what i've tried for reading

NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDir = [paths objectAtIndex:0];

NSString * filePath = [NSString stringWithFormat:@"%@/list.txt",documentsDir];

NSData * data = [[NSData alloc] initWithContentsOfFile:filePath];
NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
NSMutableDictionary * dictionary = [unarchiver decodeObjectForKey:@"mylist"];
[unarchiver finishDecoding];

and this is what i've tried for writing to the file

NSMutableData * data = [[NSMutableData alloc]init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
[archiver encodeObject:myDictionary forKey:@"mylist"];
[archiver finishEncoding];

NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDir = [paths objectAtIndex:0];

NSString * filePath = [NSString stringWithFormat:@"%@/list.txt",documentsDir];

[data writeToFile:filePath atomically:YES];
tshepang
  • 12,111
  • 21
  • 91
  • 136
  • 1
    Have you confirmed that the data is written successfully, i.e., that the file contains the correct data? – jcm Nov 28 '13 at 13:48
  • 2
    can you post your `encodeWithCoder:` and `initWithCoder:` methods from the class you wrote? – Firoze Lafeer Nov 28 '13 at 13:52
  • data is a file is made and there is something written in the file – user2074701 Nov 28 '13 at 14:41
  • @FirozeLafeer -(id)initWithCoder:(NSCoder *)aDecoder { self = [super init]; if (!self) { _title = [aDecoder decodeObjectForKey:@"title"]; _length = [aDecoder decodeObjectForKey:@"length"]; _genre = [aDecoder decodeObjectForKey:@"genre"]; NSNumber *temp = [aDecoder decodeObjectForKey:@"running"]; _isRunning = temp.boolValue; } return self; } – user2074701 Nov 28 '13 at 14:41
  • @FirozeLafeer thanks man i think i figured it out – user2074701 Nov 28 '13 at 14:47

0 Answers0