1
votes

I'm trying to decode my object from NSUserdefaults. If I debug the function initWithCoder, it's executed okay, but when I look at my object that was decoded, all the properties are nil.

My initWithCoder function:

-(id)initWithCoder:(NSCoder *)decoder
{
    self = [super init];
    if ( self != nil )
    {
        //decode the properties
        self.SGTIN = [decoder decodeObjectForKey:@"SGTIN"];
        self.GTIN = [decoder decodeObjectForKey:@"GTIN"];
        self.SerialNumber = [decoder decodeObjectForKey:@"SerialNumber"];
        self.Product = [decoder decodeObjectForKey:@"Product"];
        self.DateTimeScanned = [decoder decodeObjectForKey:@"DateTimeScanned"];
        self.Loaded = [decoder decodeBoolForKey:@"Loaded"];
    }
    return self;
}

My code to decode the object: NSDictionary *tempDictionary = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];

            NSArray *tempArray =[tempDictionary allKeys];

            for (NSString *key in tempArray){
                if ([key length] > 8) {
                    if ([[key substringToIndex:8] isEqualToString:@"INXITEM:"]) {

                        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

                        NSData *encodedObject = [defaults objectForKey:key];

                        ScannedItem *SITemp = (ScannedItem *)[NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
                    }
                }
            }

Just found it...

It was because the property Loaded (bool) is a new property and the object that was saved in NSUserDefaults didn't contain that property.

Cleared my NSUserDefaults and everything is okay now...

2
What is the superclass of ScannedItem. When and how are you encoding the instances? Have you implemented the encoding properly? - Wain

2 Answers

0
votes

You aren't calling the correct superclass method.

It should be

self = [super initWithCoder:decoder];
0
votes

Try using - (void)encodeWithCoder:(NSCoder *)coder method in ScannedItem object class

- (void)encodeWithCoder:(NSCoder *)coder {

     [coder encodeObject:self.SGTIN forKey:@"SGTIN"];
     //encode all properties
}