Reputation: 2639
I encode like this:
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:data forKey:@"Object"];
[archiver finishEncoding];
Then, after retrieving the saved file from disk I try to decode it like this:
Object *object = (Object*)[unarchiver decodeObjectForKey:@"Object"];
The problem is that this is never decoded back into Object* type. It remains NSMutableData. So when I try to access some property of object like "object.name" I get -[NSConcreteMutableData name]: unrecognized selector sent to instance 0x2c8510'.
I followed Ray Wenderlich's tutorial http://www.raywenderlich.com/1914/how-to-save-your-app-data-with-nscoding-and-nsfilemanager. Even though his code works, mine doesn't. So after a day of messing with this I am asking for some help.
Upvotes: 0
Views: 823
Reputation: 2290
The tutorial you cite uses a property called "data" on the class and also variable called "data" in the saveData method. He writes the property "_data" (or at least the synthesized instance variable _data) to the NSMutableData object "data" when he calls encodeObject:. It's a bit confusing because he's using the same name for two different things.
You, otoh, are creating an ivar named "data" and then sending that to encodeObject:. You're never accessing your Object* property, just writing an empty NSMutableData into a NSMutableData. The difference is a lack of an underscore, but there's a better way imho.
I recommend you rename the property of the data you're trying to encode to, say, "info" (or maybe something more informative, like "stockPrices" or "todaysWeather" or whatever data this class is storing)
@property Object* info;
and rename your accessor appropriately (assuming you're doing things the way he did)
and then write:
[archiver encodeObject:self.info forKey:@"Object"]
Two things are happening here for your benefit as a developer: You're using different names for the data being encoded and the info that you're encoding, and you're explicitly writing in code that says that you're accessing your class's info property, not some local variable. Both of these will make your life easier 6 months from now when you're reviewing this code.
Upvotes: 2
Reputation: 21383
It's because you're encoding data
not object
. Change this line:
[archiver encodeObject:data forKey:@"Object"];
to this
[archiver encodeObject:object forKey:@"Object"];
Upvotes: 1