NSData on custom class?

后端 未结 1 702
名媛妹妹
名媛妹妹 2021-01-15 13:28

I am about to look into bluetooth interaction on the iPhone. Now, i read that the only object that can be transferred is an NSData object. Now, i wanna transfer my \"charact

相关标签:
1条回答
  • 2021-01-15 14:05

    It sounds like you're really just asking how to implement -encodeWithCoder: and -initWithCoder:. It's pretty straightforward:

    -(void) encodeWithCoder:(NSCoder *)encoder
    {
        [encoder encodeObject:characterImage forKey:@"character image"];
        [encoder encodeInt:health forKey:@"health"];
        [encoder encodeObject:name forKey:@"name"];
    }
    

    That's all. -initWithCoder: works exactly the same way, except you call the complementary methods, such as: characterImage = [decoder decodeObjectForKey:@"character image"];.

    If you need to provide the data in a particular format to work with the target device that doesn't support the archive format, you can do that instead and use the -encodeBytes:length:forKey: method to store whatever you like, or write data in your own format into a NSMutableData object and then use -encodeObject:forKey: on that. Your target device may still need to find your data in whatever envelope the encoder stores it; you can make that easier by starting with a known series of bytes. I'm not sure whether that's necessary in your case, but it's something to keep in mind.

    0 讨论(0)
提交回复
热议问题