xcode 什么时候调用 initWithCoder?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3741946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:45:34  来源:igfitidea点击:

When does initWithCoder get called?

objective-carrayscocoa-touchxcodenscoder

提问by node ninja

This will load an array

这将加载一个数组

- (id)initWithCoder:(NSCoder*) coder
{
    self = [super initWithCoder: coder];
    if (self) {
        myArray=[coder decodeObjectForKey:@"myArray"];
    }
    return self;
}

What is the code that will call this function so that the array can be loaded?

调用此函数以便加载数组的代码是什么?

回答by DarkDust

The initWithCoder:methods are used for deserializing using NSCoding protocol, e.g. via [NSKeyedUnarchiver unarchiveObjectWithFile:]. For details see the Archives and Serializations Programming Guide, especially the Encoding and Decoding Objectssection.

这些initWithCoder:方法用于使用NSCoding 协议进行反序列化,例如通过[NSKeyedUnarchiver unarchiveObjectWithFile:]。有关详细信息,请参阅存档和序列化编程指南,尤其是编码和解码对象部分。

回答by Max Seelemann

As DarkDust said, it's called when a NSUnarchiver or a NSKeyedUnarchiver is used. However, this is not necessarily the own case. One could actually implement a custom NSCoder and according NSDecoder .. e.g. to encode/decode yaml etc...

正如 DarkDust 所说,当使用 NSUnarchiver 或 NSKeyedUnarchiver 时会调用它。然而,这不一定是自己的情况。实际上可以实现自定义 NSCoder 并根据 NSDecoder .. 例如编码/解码 yaml 等...

The most common use case is when loading nib files, as those contents are archived.

最常见的用例是加载 nib 文件时,因为这些内容已存档。