Reputation: 797
I have the following objective-c class:
@interface LatLongData {
NSMutableString *_lat;
NSMutableString *_long;
NSMutableString *_altitude;
}
-(LatLongData*) initWithLat:(NSMutableString*) latitude Long:(NSMutableString*) longitude Altitude:(NSMutableString*) altitude;
@end
How can I store/load an instance of that object? I have tried working with code like this:
LatLongData *data = [[LatLongData alloc] initWithLat:_lat Long:_long Altitude:_altitude];
// Save
NSData *theData = [NSKeyedArchiver archivedDataWithRootObject:data];
[[NSUserDefaults standardUserDefaults] setObject:theData forKey:LatLongDataKey];
//...
// Load
NSData *loadedData = [[NSUserDefaults standardUserDefaults] dataForKey:LatLongDataKey];
LatLongData *ldata = (LatLongData *)[NSKeyedUnarchiver unarchiveObjectWithData:theData];
But I have no luck with that... I know I should read everything about Core Data. I will but at this point it would be very nice to get my little sample to work.
Upvotes: 1
Views: 128
Reputation: 3294
You need to use NSCoding protocol with your class.
@interface LatLongData <NSCoding>
Here are a few protocol methods:
- (id)initWithCoder:(NSCoder *)aDecoder
{
if ((self = [super init])) {
lat = [[aDecoder decodeObjectForKey:@"lat"] copy];
long = [[aDecoder decodeObjectForKey:@"long"] copy];
alt = [[aDecoder decodeObjectForKey:@"alt"] copy];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:lat forKey:@"lat"];
[aCoder encodeObject:long forKey:@"long"];
[aCoder encodeObject:alt forKey:@"alt"];
}
P.S. You need to replace theData
at your last line with loadedData
Upvotes: 3