我试图将NSData拆分成更小的< 100长度块,以便我可以通过CoreBluetooth发送它们但是由于某种原因,它决定偶尔搞乱,事实证明,试图结合数据和从同一方法中解码对象失败。因此,我假设我将NSData拆分错误了吗?
以下是我用来拆分它的代码(取自stackoverflow上的某些陌生人!)
// Split up the data and put into Array
NSUInteger length = [data length];
NSUInteger chunkSize = 100;
NSUInteger offset = 0;
do {
NSUInteger thisChunkSize = length - offset > chunkSize ? chunkSize : length - offset;
NSData* chunk = [NSData dataWithBytesNoCopy:(char *)[data bytes] + offset
length:thisChunkSize freeWhenDone:NO];
offset += thisChunkSize;
[orderQueue addObject:chunk];
} while (offset < length);
然后重新组合数据,并将对象取消存档:
NSMutableData *finishedData = [[NSMutableData alloc] init];
for (NSData *dataChunk in orderQueue) {
[finishedData appendData:dataChunk];
}
Order *order = [NSKeyedUnarchiver unarchiveObjectWithData:finishedData]; // ERRORS OUT ON THIS LINE
finishedData = [[NSMutableData alloc] init];
dataChunks = [[NSMutableArray alloc] init];
在纸面上,老实说,我认为我做得对,但它偶尔也会漏掉。任何想法为什么会这样? :其中我收到以下错误:
*由于未捕获的异常终止应用程序&#39; NSInvalidArgumentException&#39;,原因:&#39; * - [NSKeyedUnarchiver initForReadingWithData:]:难以理解的存档(0x62,0x70,0x6c,0x69 ,0x73,0x74,0x30,0x30)&#39;
答案 0 :(得分:0)
我刚刚运行此代码来检查您的逻辑并且它是正确的。
NSMutableArray *orderQueue = [[NSMutableArray alloc] init];
NSString *originalString = @"Here are some strings for you.";
for (NSInteger i = 0; i < 1000; ++i)
{
@autoreleasepool {
originalString = [originalString stringByAppendingString:@"\nHere are some strings for you."];
}
}
NSData *data = [originalString dataUsingEncoding:NSUTF8StringEncoding];
// Split up the data and put into Array
NSUInteger length = [data length];
NSUInteger chunkSize = 100;
NSUInteger offset = 0;
do {
NSUInteger thisChunkSize = length - offset > chunkSize ? chunkSize : length - offset;
NSData* chunk = [NSData dataWithBytesNoCopy:(char *)[data bytes] + offset
length:thisChunkSize freeWhenDone:NO];
offset += thisChunkSize;
[orderQueue addObject:chunk];
} while (offset < length);
NSMutableData *finishedData = [[NSMutableData alloc] init];
for (NSData *dataChunk in orderQueue) {
[finishedData appendData:dataChunk];
}
NSString *recreatedString = [[NSString alloc] initWithData:finishedData encoding:NSUTF8StringEncoding];
NSLog(@"%@", recreatedString);
NSLog(@"%@", [originalString isEqualToString:recreatedString] ? @"Equal" : @"Error");
您的错误必须在其他地方,可能与您在<NSCoding>
课程中对Order
协议做出回应的方式有关。