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

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I'm not sure that you can call: self = [super initWithCoder:aDecoder] but self = [super init]; NSObject doesn't support this protocol by default
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...

1 Comment

This is very bad approach. You should never use accessors in init method

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.