1

I was reading about initializing the archived objects from a XIB file and found that

- (id)initWithCoder:(NSCoder *)aDecoder 

is a way of doing it. But I am not able to get a hang around this. Can someone show me an simple example of how to do this?

Thanks a ton

Neelesh
  • 3,673
  • 8
  • 47
  • 78

2 Answers2

4

The NSCoder class is used to archive/unarchive (marshal/unmarshal, serialize/deserialize) of objects.

This is a method to write objects on streams (like files, sockets) and being able to retrieve them later or in a different place.

I would suggest you to read Archiving

You also need to define the following method as follows:

- (void)encodeWithCoder:(NSCoder *)enCoder 
{ 
    [super encodeWithCoder:enCoder];

    [enCoder encodeObject:instanceVariable forKey:INSTANCEVARIABLE_KEY];

    // Similarly for the other instance variables.
    ....
}

And in the initWithCoder method initialize as follows:

- (id)initWithCoder:(NSCoder *)aDecoder 
{
    if(self = [super initWithCoder:aDecoder]) {
        self.instanceVariable = [aDecoder decodeObjectForKey:INSTANCEVARIABLE_KEY];

       // similarly for other instance variables
       ....
}
    return self;
}

You can initialize the object standard way i.e

CustomObject *customObject = [[CustomObject alloc] init];

Example taken from this answer

Community
  • 1
  • 1
Paresh Navadiya
  • 38,095
  • 11
  • 81
  • 132
  • I'm not sure that you can call: self = [super initWithCoder:aDecoder] but self = [super init]; NSObject doesn't support this protocol by default – Bogdan Apr 20 '15 at 22:30
4

You can use it in following way:

.h file

@interface Score : NSObject {
    NSString *Username;
    NSString *TotalPoints;
    NSString *LifeRemains;
    NSString *ScoreDate;
}

@property (nonatomic, retain) NSString *Username;
@property (nonatomic, retain) NSString *TotalPoints;
@property (nonatomic, retain) NSString *LifeRemains;
@property (nonatomic, retain) NSString *ScoreDate;

in .m file

@synthesize Username, TotalPoints, LifeRemains, ScoreDate;

- (void)encodeWithCoder:(NSCoder *)encoder
{
//Encode properties, other class variables, etc
[encoder encodeObject:self.Username forKey:kScoreUsername];
[encoder encodeObject:self.TotalPoints forKey:kScoreTotalPoints];
[encoder encodeObject:self.LifeRemains forKey:kScoreLifeRemains];
[encoder encodeObject:self.ScoreDate forKey:kScoreDate];
}

- (id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if( self != nil )
{
    //decode properties, other class vars
    self.Username = [decoder decodeObjectForKey:kScoreUsername];
    self.TotalPoints = [decoder decodeObjectForKey:kScoreTotalPoints];
    self.LifeRemains = [decoder decodeObjectForKey:kScoreLifeRemains];
    self.ScoreDate = [decoder decodeObjectForKey:kScoreDate];
}
return self;
}

Happy Coding...

Nishant B
  • 2,897
  • 1
  • 18
  • 25