NSData on custom class?

2019-02-19 11:58发布

问题:

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 "character" objects. The class looks something like this:

@interface Character : NSObject <NSCoding>
{
   UIImage *characterImage;
   int health;
   NSString *name;
}

-(void) initWithStats;
-(void) addToViewController: (UIViewController *)theView;

-(void) encodeWithCoder:(NSCoder *)encoder;
-(void) initWithCoder:(NSCoder *)decoder;

@end

Now, i know that i have to conform to the NSCoding protocol and implement those 2 methods, however, i am not quite sure what to do here. I know i somehow need to be able to make instances of this class and then "unpack / unarchieve" them when the NSData object is received by the other device.

So, any advice here is greatly appreciated :=) i am very new to bluetooth programming and have never worked with that or the NSData before. So thanks on advance :)

/JBJ

回答1:

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.