我正试图通过wifi / blutooth从一个iphone发送信息字典到另一个iphone,为此我实现了CFnetwork和NSNetservice Concept.I在Reciver端收到了数据。
我的代码如下....
**Sender Side**
samDict=[NSMutableDictionary dictionary];
[samDict setObject:@"Muhammed Musthafa" forKey:@"PP"];
[samDict setObject:@"John P" forKey:@"Jose"];
[samDict setObject:@"Lubaba" forKey:@"P"];
[samDict setObject:@"JINI" forKey:@"KS"];
[samDict setObject:@"Anusha" forKey:@"GS"];
[samDict setObject:@"Athulya" forKey:@"V"];
[samDict setObject:@"Riyas" forKey:@"MM"];
[samDict setObject:@"Raihanath" forKey:@"MH"];
[samDict setObject:@"Shabeer" forKey:@"poola"];
[samDict setObject:@"Rajisha" forKey:@"Raji"];
//NSLog(@" Dictionary values.............%@",samDict);
NSMutableData *ArchiveData=[[NSMutableData alloc]init];
NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc]initForWritingWithMutableData:ArchiveData];
[archiver setOutputFormat: NSPropertyListXMLFormat_v1_0];
[archiver encodeObject:self.samDict forKey:@"Some Key Values"];
[archiver finishEncoding];
[archiver release];
const uint8_t *buffer=(const uint8_t *)[ArchiveData bytes];
NSInteger nWrtitten=[_outStream write:buffer maxLength:[ArchiveData legth]];
if (!nWrtitten)
{
NSLog(@"Eorror writting to Stream %@ : %@", _outStream, [_outStream streamError]);
}
else
{
NSLog(@" Write %ld bytes to Stream %@",(long)nWrtitten, _outStream);
}
接收方
NSInteger bytesRead;
uint8_t buffer[13000];
NSMutableData *data=[[NSMutableData data]retain];
if (stream==_inStream)
{
bytesRead=[_inStream read:buffer maxLength:sizeof(buffer)];
if (bytesRead==-1&& bytesRead==0)
{
NSLog(@"_inStream Error...................");
}
else
{
[data appendBytes:buffer length:bytesRead];
NSLog(@"Data Received has length :%d\n\n",[data length]);
NSLog(@"data............%@",data);
}
}
我在Receiver Side获得了数据。这是以字节格式。我无法在Receiver方面取消存档此数据。如果我试图将此格式解压缩为这样的字典格式
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSMutableDictionary* UnArchiveDictionary =[NSMutableDictionary dictionary];
UnArchiveDictionary = [[unarchiver decodeObjectForKey:@"Some Key Values"] retain];
NSLog(@"UnArchive Dictionary %@",UnArchiveDictionary);
但遗憾的是,不能以字典格式取消归档此数据。我收到了行NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
的错误
我找到了一些代码,用于将字节数据转换为字符串格式,如此
size_t length=[data length];
unsigned char aBuffer[length];
[data getBytes:aBuffer length:length];
aBuffer[length - 1]=0;
NSString *messageString =aBuffer;
NSLog (@"%s",messageString);
但我的问题是如何取回相同的字典。为什么在Unarchived时间内收到错误?
答案 0 :(得分:0)
问题可能是条件:
if (bytesRead==-1&& bytesRead==0)
总是假的。变量不能同时具有两个不同的值。你可能想要:
if (bytesRead==-1 || bytesRead==0)
因此,如果发生错误(或者没有传输数据),您的代码就不会注意到,而是将堆栈中的垃圾字节附加到您的可变数据中。
keyed unarchiver然后尝试将这些垃圾字节解释为存档并注意到它不存在,因此它会引发异常。