Objective C - 如何使用initWithCoder方法? [英] Objective C - How do I use initWithCoder method?
本文介绍了Objective C - 如何使用initWithCoder方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下方法为我的类打算加载一个nib文件并实例化对象:
I have the following method for my class which intends to load a nib file and instantiate the object:
- (id)initWithCoder:(NSCoder*)aDecoder
{
if(self = [super initWithCoder:aDecoder]) {
// Do something
}
return self;
}
如何实例化这个类的对象?
这是 NSCoder
?如何创建它?
How does one instantiate an object of this class?
What is this NSCoder
? How can I create it?
MyClass *class = [[MyClass alloc] initWithCoder:aCoder];
推荐答案
您还需要定义以下方法如下:
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.
....
}
并且在initWithCoder方法中初始化如下
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];
这篇关于Objective C - 如何使用initWithCoder方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文