如何序列化包含 NSData 的对象?
我正在尝试序列化一个包含多个数据字段的对象...其中一个字段的数据类型为 NSData,不会序列化。我已按照 http://www.isolated.se 但我的代码(见下文)导致错误“[NSConcreteData data]:无法识别的选择器发送到实例...”。如何序列化我的对象?
头文件:
@interface Donkey : NSObject<NSCoding>
{
NSString* s;
NSData* d;
}
@property (nonatomic, retain) NSString* s;
@property (nonatomic, retain) NSData* d;
- (NSData*) serialize;
@end
实现文件:
@implementation Donkey
@synthesize s, d;
static NSString* const KEY_S = @"string";
static NSString* const KEY_D = @"data";
- (void) encodeWithCoder:(NSCoder*)coder
{
[coder encodeObject:self.s forKey:KEY_S];
[coder encodeObject:self.d forKey:KEY_D];
}
- (id) initWithCoder:(NSCoder*)coder;
{
if(self = [super init])
{
self.s = [coder decodeObjectForKey:KEY_S];
self.d = [coder decodeObjectForKey:KEY_D];
}
return self;
}
- (NSData*) serialize
{
return [NSKeyedArchiver archivedDataWithRootObject:self];
}
@end
I'm trying to serialize an object containing a number of data fields...where one of the fields is of datatype NSData which won't serialize. I've followed instructions at http://www.isolated.se but my code (see below) results in the error "[NSConcreteData data]: unrecognized selector sent to instance...". How do I serialize my object?
Header file:
@interface Donkey : NSObject<NSCoding>
{
NSString* s;
NSData* d;
}
@property (nonatomic, retain) NSString* s;
@property (nonatomic, retain) NSData* d;
- (NSData*) serialize;
@end
Implementation file:
@implementation Donkey
@synthesize s, d;
static NSString* const KEY_S = @"string";
static NSString* const KEY_D = @"data";
- (void) encodeWithCoder:(NSCoder*)coder
{
[coder encodeObject:self.s forKey:KEY_S];
[coder encodeObject:self.d forKey:KEY_D];
}
- (id) initWithCoder:(NSCoder*)coder;
{
if(self = [super init])
{
self.s = [coder decodeObjectForKey:KEY_S];
self.d = [coder decodeObjectForKey:KEY_D];
}
return self;
}
- (NSData*) serialize
{
return [NSKeyedArchiver archivedDataWithRootObject:self];
}
@end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题很可能是由于使用
data
作为属性名称引起的命名冲突,因为否则代码看起来很好,并且 NSString 和 NSData 都应该很容易序列化。尝试将
data
重构为“theData”或“myData”之类的内容,看看问题是否解决。Your problem is most likely a naming collision caused by using
data
as a property name because otherwise the code looks fine and both NSString and NSData should serialize easily.Try refactoring
data
into something like "theData" or "myData" and see if the issue resolves.