jkigel
jkigel

Reputation: 1592

NSData to Custom NSObject

I'm trying to transfer data between 2 devices using bluetooth. Device A is holding custom NSObject. Device B is receiving this custom NSObject as NSData.

What is the best way to decode the received NSData into a custom NSObject ?

Thanks!

Upvotes: 2

Views: 5873

Answers (1)

samvermette
samvermette

Reputation: 40437

You have to implement the encodeWithCoder: and initWithCoder: methods of your custom object so it knows how to get encoded and decoded into/from an NSData object:

- (void)encodeWithCoder:(NSCoder *)coder{
    [coder encodeObject:self.property forKey:@"property"];
    // all other properties
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.property = [decoder decodeObjectForKey:@"property"];
        // all other properties
    }
    return self;
}

And then you decode it from NSData to NSObject using:

NSObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:data];

The other way around:

[NSKeyedArchiver archiveRootObject:object toFile:self.filePath];

Upvotes: 10

Related Questions