Saranjith
Saranjith

Reputation: 11567

Pass value using NSCoding Protocol

I'm trying to pass data to detail page upon clicking a cell inside UITabelViewCell using NSCoding Protocol

NSCoder *coder =[[NSCoder alloc] init];

[coder encodeObject:@"value" forKey:@"title"];

[coder encodeObject:cell.remainderContentLabel.text forKey:@"content"];

[coder encodeObject:cell.remainderDateTimeLabel.text forKey:@"datetime"];

[coder encodeObject:cell.remainterImageView.image forKey:@"image"];

RemainderDetailViewController *detailVC = [[RemainderDetailViewController alloc] initWithCoder:coder];

[self.navigationController pushViewController:detailVC animated:YES];

But it is crashing msg is

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -encodeObject:forKey: cannot be sent to an abstract object of class NSCoder: Create a concrete instance!'

In detail page decoding is done by

- (id) initWithCoder:(NSCoder *) aDecoder {

    if(self = [super initWithCoder:aDecoder]) {

      _remainderTitle.text =  [aDecoder decodeObjectForKey:@"title"];

      _remainderDetails.text =  [aDecoder decodeObjectForKey:@"content"];

      _dateAndTime.text =   [aDecoder decodeObjectForKey:@"datetime"];

      _remainderImage.image =  [aDecoder decodeObjectForKey:@"image"];

    }

    return self;
}

How to use

- (void)encodeWithCoder:(NSCoder *)encoder

What is wrong im doing? Class is confirmed to NSCopying protocol

Upvotes: 0

Views: 412

Answers (2)

Ax1le
Ax1le

Reputation: 6643

AS I know - (id) initWithCoder:(NSCoder *) aDecoder is called when you load a ViewController from storyboard. If you want to push to a ViewController in the storyboard using code. You can

RemainderDetailViewController *detailVC = [[UIStoryboard storyboardWithName:@"XXX" bundle:nil] instantiateViewControllerWithIdentifier:@"yourControllerIdentifier"];
detailVC.paramDic = @{...};
[self.navigationController pushViewController:detailVC animated:YES];

The "yourControllerIdentifier" is defined in the storyboard.You can't initialize a ViewController by using the method directly. And in the destination ViewController - (id) initWithCoder:(NSCoder *) aDecoder can be fired. You can do some initial work in it.

Upvotes: 1

Willeke
Willeke

Reputation: 15587

Use a dictionary to pass a bunch of objects.

But if you want to use an archive, read the documentation of NSCoder, it says:

The NSCoder abstract class declares the interface used by concrete subclasses to transfer objects and other values between memory and some other format.

The concrete subclasses provided by Foundation for these purposes are NSArchiver, NSUnarchiver, NSKeyedArchiver, NSKeyedUnarchiver, and NSPortCoder.

Use NSKeyedArchiver.

Upvotes: 0

Related Questions