initWithCoder用于加载xib示例

时间:2012-05-21 12:50:32

标签: iphone objective-c interface-builder

我正在阅读有关从XIB文件初始化已归档对象的信息,并发现

- (id)initWithCoder:(NSCoder *)aDecoder 

是一种做法。但我无法解决这个问题。有人能告诉我一个如何做到这一点的简单例子吗?

非常感谢

2 个答案:

答案 0 :(得分:4)

NSCoder类用于archive/unarchive的{​​{1}}(编组/解组,序列化/反序列化)。

这是一种在流(如文件,套接字)上编写对象并能够在以后或在不同的地方检索它们的方法。

我建议你阅读Archiving

您还需要按如下方式定义以下方法:

objects

在initWithCoder方法中初始化如下:

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

    [enCoder encodeObject:instanceVariable forKey:INSTANCEVARIABLE_KEY];

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

您可以初始化对象标准方式,即

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

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

取自this answer

的示例

答案 1 :(得分:4)

您可以通过以下方式使用它:

.h文件

@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;
<。>文件中的

@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;
}

快乐编码......