xcode NSCoder - 使用多级嵌套数组编码数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9343570/
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 23:20:33  来源:igfitidea点击:

NSCoder - Encoding an Array, with multiple levels of nested arrays

objective-ciosxcodesaving-datanscoder

提问by Charl

I have a mainObjectArray (NSMutableArray) which is populated with instances of a custom class. Each instance is itself an array, and objects in each array are NSDates, NSStrings, BOOL, and more arrays containing similar objects.

我有一个 mainObjectArray (NSMutableArray),它填充了自定义类的实例。每个实例本身就是一个数组,每个数组中的对象是 NSDates、NSStrings、BOOL 以及更多包含类似对象的数组。

What I haven't been able to establish is whether it's possible to, inside the

我无法确定的是是否有可能,在

- (void)encodeWithCoder:(NSCoder *)encoder 

method, to just say something like that:

方法,只是说这样的话:

[encoder encodeWithObject:mainObjectArray];

Or do have to encode every object in every instance separately? This would be a bit of a pain...

还是必须分别对每个实例中的每个对象进行编码?这会有点痛...

Your help would be very much appreciated.

您的帮助将不胜感激。

回答by cocoakomali

Just implement the encoding and decoding methods in your custom class. That will do. Some sample,

只需在您的自定义类中实现编码和解码方法。那就行了。一些样品,

- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:[NSNumber numberWithInt:pageNumber] forKey:@"pageNumber"];
    [encoder encodeObject:path forKey:@"path"];
    [encoder encodeObject:array forKey:@"array"];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if(self = [super init]) 
    {
        self.pageNumber = [[aDecoder decodeObjectForKey:@"pageNumber"] intValue];
        self.path = [aDecoder decodeObjectForKey:@"path"];
        self.array = [aDecoder decodeObjectForKey:@"array"];
    }
}

You can see totally three data types being encoded and decoded - int, string, array.

您可以看到总共被编码和解码的三种数据类型——int、string、array。

Hope this helps.

希望这可以帮助。