Search code examples
iosobjective-cnsdatansobject

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!


Solution

  • 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];