如何序列化包含 NSData 的对象?

发布于 2024-08-28 19:06:20 字数 1119 浏览 2 评论 0原文

我正在尝试序列化一个包含多个数据字段的对象...其中一个字段的数据类型为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

看海 2024-09-04 19:06:20

您的问题很可能是由于使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文