tags:

views:

512

answers:

3

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

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

NSData *dataOnObject = [NSKeyedArchiver archivedDataWithRootObject:classObject];

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.

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

Any help would be greatly appreciated ...

awaiting for your reply ...

+2  A: 

you can only archive objects that support the NSCoding protocol

newacct
+2  A: 

You need to implement encodeWithCoder: on your custom class, serializing all of its attributes using the NSCoder passed into it. If its attributes include any more custom classes, they'll need encodeWithCoder: implementing too.

jdelStrother
A: 

Instead of

NSData *dataOnObject = [NSKeyedArchiver archivedDataWithRootObject:classObject];

it should be

NSData *dataOnObject = [[NSUserDefaults standardUserDefaults] objectForKey:@"someKey"];

But that's just for reading data in that's already been saved. If you want to save an object as NSData then you have this:

[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:classObject] forKey:@"someKey"];

But that's not all. Your classObject has to implement the NSCoding protocol and have the two methods encodeWithCoder: and initWithCoder: since it's not an NS object in order for it to work.

awakeFromNib