Objective c 目标C-如何使用initWithCoder方法?
我的类有以下方法,用于加载nib文件并实例化对象:Objective c 目标C-如何使用initWithCoder方法?,objective-c,cocoa-touch,nscoder,Objective C,Cocoa Touch,Nscoder,我的类有以下方法,用于加载nib文件并实例化对象: - (id)initWithCoder:(NSCoder*)aDecoder { if(self = [super initWithCoder:aDecoder]) { // Do something } return self; } 如何实例化这个类的对象? 这是什么NSCoder?如何创建它 MyClass *class = [[MyClass alloc] initWithCoder:a
- (id)initWithCoder:(NSCoder*)aDecoder
{
if(self = [super initWithCoder:aDecoder]) {
// Do something
}
return self;
}
如何实例化这个类的对象?
这是什么NSCoder
?如何创建它
MyClass *class = [[MyClass alloc] initWithCoder:aCoder];
NSCoder
类用于归档/取消归档(封送/解封、序列化/反序列化)对象
这是一种在流(如文件、套接字)上写入对象并能够稍后或在其他位置检索它们的方法
我建议您阅读您还需要定义以下方法:
- (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;
}
在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;
}
您可以用标准方式初始化对象,即
CustomObject *customObject = [[CustomObject alloc] init];
我的主要问题是:“那么基于这个init方法,你如何实例化这个类的对象呢?”如果你使用这个对象进行序列化和反序列化,那么需要定义这些方法。您可以使用普通的init方法初始化对象,但是。。。如何调用initWithCoder方法?我想您指的是[NSKeyedUnarchiver unarchiveObjectWithData:]。检查NSKeyedUnarchiver的类方法以进行读取data@Ev您不需要调用initWithCoder,从nib或情节提要加载视图后,将调用此方法。