我正在阅读有关从 XIB 文件初始化存档对象的信息,并发现
- (id)initWithCoder:(NSCoder *)aDecoder
是一种方法。但我无法解决这个问题。有人可以告诉我一个简单的例子来说明如何做到这一点吗?
万分感谢
我正在阅读有关从 XIB 文件初始化存档对象的信息,并发现
- (id)initWithCoder:(NSCoder *)aDecoder
是一种方法。但我无法解决这个问题。有人可以告诉我一个简单的例子来说明如何做到这一点吗?
万分感谢
该类NSCoder
用于archive/unarchive
(编组/解组,序列化/反序列化)的objects
.
这是一种在流(如文件、套接字)上写入对象并能够稍后或在不同位置检索它们的方法。
我建议您阅读存档
您还需要定义如下方法:
- (void)encodeWithCoder:(NSCoder *)enCoder
{
[super encodeWithCoder:enCoder];
[enCoder encodeObject:instanceVariable forKey:INSTANCEVARIABLE_KEY];
// Similarly for the other instance variables.
....
}
并在 initWithCoder 方法中初始化如下:
- (id)initWithCoder:(NSCoder *)aDecoder
{
if(self = [super initWithCoder:aDecoder]) {
self.instanceVariable = [aDecoder decodeObjectForKey:INSTANCEVARIABLE_KEY];
// similarly for other instance variables
....
}
return self;
}
您可以以标准方式初始化对象,即
CustomObject *customObject = [[CustomObject alloc] init];
取自此答案的示例
您可以通过以下方式使用它:
.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;
在 .m 文件中
@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;
}
快乐的编码...