简体   繁体   English

使用NSCoder对NSArray或NSDictionary进行编码

[英]Encode NSArray or NSDictionary using NSCoder

I was wondering whether or not it is possible to use the NSCoder method: 我想知道是否可以使用NSCoder方法:

- (void)encodeObject:(id)objv forKey:(NSString *)key

to encode either an instance of NSArray or NSDictionary. 编码NSArray或NSDictionary的实例。 If not how do you go about encoding them? 如果不是,你怎么去编码呢? I am trying to use NSKeyedArchived / NSKeyedUnarchiver to send data between phones using GameKit. 我正在尝试使用NSKeyedArchived / NSKeyedUnarchiver使用GameKit在手机之间发送数据。 I tried it and cannot seem to retrieve the string I stored in my array. 我试过它,似乎无法检索我存储在我的数组中的字符串。 The packet class I made comes through along with the packet type integer, but not the data in the array it seems. 我创建的数据包类与数据包类型整数一起出现,但不是数组中的数据。

Thanks in advance! 提前致谢!

If the array or dictionary is the root object you should do 如果数组或字典是您应该执行的根对象

NSData * encodedData = [NSKeyedArchiver archivedDataWithRootObject:someArray];

or 要么

BOOL success = [NSKeyedArchiver archiveRootObject:someArray toFile:filePath];

If it is an instance variable of a custom class, in the -encodeWithCoder: method should do 如果它是自定义类的实例变量,则在-encodeWithCoder:方法中应该这样做

[coder encodeObject:someArray forKey:@"someArray"];

and then in the -initWithCoder: method 然后在-initWithCoder:方法中

someArray = [[coder decodeObjectForKey:@"someArray"] retain];

What kind of objects are you storing in the array? 你在数组中存储了什么样的对象? Make sure that all objects stored in the array implement the NSCoding protocol. 确保存储在阵列中的所有对象都实现NSCoding协议。

NSKeyedArchiver/Unarchiver should encode and decode NSArrays and NSDictionaries with no problem. NSKeyedArchiver / Unarchiver应该编码和解码NSArrays和NSDictionaries没有问题。 If your packet class you've created implements the NSCoding protocol, you need to explicitly call [encodeObject: myNsArray forKey:@"stringsArray"] in your -encodeWithCoder: method (assuming that myNsArray is the name of the instance variable in your packet object you want to encode). 如果您创建的数据包类实现了NSCoding协议,则需要在-encodeWithCoder:方法中显式调用[encodeObject: myNsArray forKey:@"stringsArray"] (假设myNsArray是数据包对象中实例变量的名称)你想编码)。 But then the archiver and NSArray should take care of the rest of it. 但是归档者和NSArray应该照顾其余部分。 If you're doing this, it would be helpful to hear more about the layout of your classes and who's calling who when encoding/decoding. 如果您正在这样做,那么了解更多关于类的布局以及在编码/解码时谁在调用谁将会很有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM