2014-11-13 95 views
0

我試圖把NSData分成更小的< 100個長度的塊,所以我可以通過CoreBluetooth發送它們,但由於某種原因,它決定偶爾會搞砸,事實證明,試圖結合數據和解碼對象在同一個方法內失敗。正因爲如此,我假設我分裂了NSData錯誤?如何正確拆分NSData?

這裏是我使用它分裂的代碼(從某種陌生人採納的計算器!)

// 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]; 

在紙上,我真的認爲我做得對,但偶爾也會出錯。任何想法,爲什麼這可能是? :<我收到以下錯誤:

*終止應用程序由於未捕獲的異常 'NSInvalidArgumentException',原因是:「* - [NSKeyedUnarchiver initForReadingWithData:]:難以理解的存檔(0X62,0x70,0x6c,0×69(0x73)的,0x74 ,0x30,0x30)'

+1

我想知道如何使用'dataWithBytesNoCopy',因爲原始的NSData對象可能隨時會告別。所以你將一個NSData的內部地址存儲在另一個NSData中,那麼第一個NSData就會消失,你會得到什麼?垃圾,我懷疑。 –

+0

@HotLicks:' - [NSData bytes]'是用'objc_inner_pointer'標記的,在這裏[將確保](http://lists.apple.com/archives/cocoa-dev/2012/May/msg00469.html) 「數據」會像「塊」一樣長。 –

回答

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類。