Search code examples
objective-ciosobjectpropertiesnskeyedarchiver

Changing Value of Objects property doesn't work for object created using NSKeyedUnarchiver


I am trying to Change the value of an Object's property (Unarchived from .plist) and it doesn't seem to work... I Am trying to figure out whats wrong for a while now and I would really appreciate any help.

The Code:

NSArray * pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * pathToSave = [[pathArray objectAtIndex:0] stringByAppendingPathComponent:@"ownProfileArchive"];
OwnProfileData * OwnProfile = [NSKeyedUnarchiver unarchiveObjectWithFile:pathToSave];
[OwnProfile setName:[NameField text]]; // at that point, even if I change the name to a string saying "Hello!", It would always be NULL! 
NSLog(@"Name = %@", [OwnProfile Name]); // Here I can see it is always null.
[NSKeyedArchiver archiveRootObject:OwnProfile toFile:pathToSave];

Now I For the first time this runs, It is possible there isn't a file at the path specified, and I assumed the app "wouldn't mind", because documentation says that NSKeyedArchiver will create a file if there isn't one in existent. The question is: If there isn't a file, Will The code for creating the object (NSKeyedUnarchiver) would create a functional object, because it does return a value o 'NULL', but I can't change it... If A file Has To Exist, What is the code for checking if file exists and creating one if it doesn't? (I think there will be a If-Else Conditional involved, but I don't know what the condition is and how to create a new file...).


Solution

  • I bet the issue is that if the file does not exist, then I suspect you aren't getting an actual instance of OwnProfileData, and hence OwnProfile is nil. Check for nil, and create a new instance in that case (which can be added to your archive for future use).

    Objective-C allows sending messages to nil, so stuff like this is hard to see. Try NSLogging OwnProfile and see!