使用 NSCoder 编码 NSArray 或 NSDictionary
我想知道是否可以使用 NSCoder 方法:
- (void)encodeObject:(id)objv forKey:(NSString *)key
对 NSArray 或 NSDictionary 的实例进行编码。如果不是,你如何对它们进行编码?我正在尝试使用 NSKeyedArchived / NSKeyedUnarchiver 在使用 GameKit 的手机之间发送数据。我尝试了一下,似乎无法检索我存储在数组中的字符串。我制作的数据包类与数据包类型整数一起出现,但看起来不是数组中的数据。
提前致谢!
I was wondering whether or not it is possible to use the NSCoder method:
- (void)encodeObject:(id)objv forKey:(NSString *)key
to encode either an instance of NSArray or NSDictionary. If not how do you go about encoding them? I am trying to use NSKeyedArchived / NSKeyedUnarchiver to send data between phones using 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果数组或字典是您应该执行的根对象
,或者
如果它是自定义类的实例变量,则应在
-encodeWithCoder:
方法中执行,然后在
-initWithCoder:< /代码> 方法
If the array or dictionary is the root object you should do
or
If it is an instance variable of a custom class, in the
-encodeWithCoder:
method should doand then in the
-initWithCoder:
method您在数组中存储什么类型的对象?确保数组中存储的所有对象都实现 NSCoding 协议。
What kind of objects are you storing in the array? Make sure that all objects stored in the array implement the NSCoding protocol.
NSKeyedArchiver/Unarchiver 应该可以毫无问题地编码和解码 NSArray 和 NSDictionaries。如果您创建的数据包类实现了 NSCoding 协议,则需要显式调用
[encodeObject:
myNsArray
forKey:@" stringsArray"]
在您的-encodeWithCoder:
方法中(假设 myNsArray 是您要编码的数据包对象中的实例变量的名称)。但是归档器和 NSArray 应该处理剩下的事情。如果您正在这样做,那么了解有关类的布局以及编码/解码时谁调用谁的更多信息将会很有帮助。NSKeyedArchiver/Unarchiver should encode and decode NSArrays and NSDictionaries with no problem. 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). But then the archiver and NSArray should take care of the rest of it. 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.