本文介绍了将NSObject转换为NSData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将 NSObject 转换为 NSData 时遇到问题。我有一个继承 NSObject 的类。

I am having an issue in converting a NSObject into NSData. I have a class which inherits NSObject.

当我试图将该特定类的对象转换为 NSData 如下:

When i tried to convert the object of that particular class into NSData as follows :

NSData *dataOnObject = [NSKeyedArchiver archivedDataWithRootObject:classObject];

但是它给出了异常声明 - [classObject encodeWithCoder:]:发送到实例的无法识别的选择器..

but it gives out exception stating that -[classObject encodeWithCoder:]: unrecognized selector sent to instance ..

我还将对象添加到新创建的数组中

I have also added the object to a newly created array as

NSMutableArray *wrapperedData = [NSMutableArray arrayWithObject: classObject];
NSData *dataOnObject = [NSKeyedArchiver archivedDataWithRootObject:value];

但是,它仍然给出例外。

But still , its giving out exception.

所以我需要从对象 classObject 中提取字节。

So I need to extract the bytes from the object classObject.

我们非常感谢任何帮助...

Any help would be greatly appreciated ...

等待您的回复......

awaiting for your reply ...

推荐答案

您必须为自己的对象实现,例如:

You must implement for your own object such as:

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInt:self.age forKey:@"age"];
    [aCoder encodeObject:self.email forKey:@"email"];
    [aCoder encodeObject:self.password forKey:@"password"];
}
BOOL success = [NSKeyedArchiver archiveRootObject:person toFile:archiveFilePath];

和:

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeIntForKey:@"age"];
        self.email = [aDecoder decodeObjectForKey:@"email"];
        self.password = [aDecoder decodeObjectForKey:@"password"];
    }
    return self;
}
Person *unarchivePerson = [NSKeyedUnarchiver unarchiveObjectWithFile:archiveFilePath];

这篇关于将NSObject转换为NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:17