Struggling restoring message Labels


#1

Hi everyone!

My approach for restoring the label messages was to add each one of the messages to a NSMutable array once all of its properties are set within the drawHypnoticMessage:message like this:

[code]



[messageLabel addMotionEffect:motionEffect];

//Add the message to the messages array
[self.messages addObject:messageLabel];

}[/code]

Then, I used encodeRestorableStateWithCoder:coder to archive this array like this:

...
...
...
    [coder encodeObject:self.messages forKey:@"hypnoticMessages"];
    [super encodeRestorableStateWithCoder:coder];

Finally I used the decodeRestorableStateWithCoder:coder to retrieve the array and add the UILabels to the view like this:

...
...
...
    NSArray *messageLabels = [[NSArray alloc] initWithArray:[coder decodeObjectForKey:@"hypnoticMessages"]];
    
    if (messageLabels) {
        for (UILabel *message in messageLabels) {
            [self.view addSubview:message];
        }
    }
    
    [super decodeRestorableStateWithCoder:coder];

And the whole thing didn’t work… xD … I set a break point at the “encoding” stuff and notice the array is filled correctly when it is about to be encoded, but then I set another breakpoint to the “decoding” stuff and realize that there was no data coming from the decoding of the “hypnoticMessages” key… somebody knows why is this happening? please…


#2

So it appears that when archiving with enableRestorableStateWithCoder a KeyedArchiver type is used for the coder but in decodeRestorableStateWithCoder a UIStateRestorationKeyedUnarchiver type is used for the coder. For some reason, the UILabel doesn’t appear to get decoded (as you’ve noticed) possibly due to the fact that a UIStateRestorationKeyedUnarchiver is used. I was scratching my head for hours on this since uilabel’s follow the NSCoding protocols.

To resolve this, I did the following:

  • (void)encodeRestorableStateWithCoder:(NSCoder *)coder
    {
    [coder encodeObject:self.circleColor forKey:@“circleColor”];

    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:self.subviews forKey:@“subviews”];
    [archiver finishEncoding];

    [coder encodeDataObject:data];

    [super encodeRestorableStateWithCoder:coder];
    }

  • (void)decodeRestorableStateWithCoder:(NSCoder *)coder
    {
    self.circleColor = [coder decodeObjectForKey:@“circleColor”];

    NSData * subviewsData = [coder decodeDataObject];

    NSKeyedUnarchiver archiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:subviewsData];
    NSArray
    subviews = [archiver decodeObjectForKey:@“subviews”];
    [archiver finishDecoding];

    for(UIView *view in subviews)
    {
    [self addSubview:view];
    }

    [super decodeRestorableStateWithCoder:coder];
    }

Hopefully this helps someone!