I have an object that I want to send to another device via bluetooth. I have successfully setup the bluetooth connection and transferred an encoded NSString; however, I haven’t figured out how to use the archiving and encoding tools correctly to send an Object.
I want to send the object defined below called ChatMessage. It implements the NSCoding delegate methods initWithCoder and encodeWithCoder as seen below.
In the second code snippet, I have the code for sending and receiving the data i.e. the methods that result in the de-encoder being called.
It keeps crashing on the last line of the decode method. I’ve been struggling to figure it out what is going wrong. Any help would be greatly appreciated!
@interface ChatMessage : NSObject <NSCoding> {
NSString *sender;
NSString *message;
}
@property (nonatomic, retain) NSString *sender;
@property (nonatomic, retain) NSString *message;
@end
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:sender forKey:@"sender"];
[coder encodeObject:message forKey:@"message"];
}
- (id)initWithCoder:(NSCoder *)coder {
sender = [[coder decodeObjectForKey:@"sender"] retain];
message = [[coder decodeObjectForKey:@"message"] retain];
return self;
}
In my View, the protocol for the PeerPicker Delegate functions.
- (void) receiveData:(NSData *)data
fromPeer:(NSString *)peer
inSession:(GKSession *)session
context:(void *)context {
ChatMessage *aMsg = [[ChatMessage alloc] init];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]
initForReadingWithData:data];
@try {
aMsg = [unarchiver decodeObjectForKey:@"myMessage"];
}
@catch (NSException *exception) {
NSLog(@"Error: %@", exception);
}
@finally {
}
if (!messages) messages = [[NSMutableArray alloc] init];
[messages addObject:aMsg];
// reload the table
[messageList reloadData];
[unarchiver finishDecoding];
[unarchiver release];
[data release];
}
— The code was crashing because I had
[data release];
I found this using the instruments tool.