2014-07-08 64 views
3

如何在我的NSMutableData的開頭插入一個字節?我知道有一個replaceBytesInRange:方法,但它只是替換字節。有一堆insertXAtIndex:方法,但沒有一個是字節。我怎樣才能做到這一點?我能想到的一種方法是:在NSMutableData前面插入字節

NSMutableData *theData = [NSMutableData dataWithBytes:myByte]; 
[theData appendData:myOriginalData]; 
myOriginalData = nil; 

但是必須有更好的方法。

我也試過,但沒有奏效:

char *sec = "Second!"; 
char *fir = "First!"; 

NSMutableData *theData = [NSMutableData dataWithBytes:(const void *)sec length:7]; 
[theData replaceBytesInRange:NSMakeRange(0, 0) withBytes:(const void *)fir]; 

NSString *str1 = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding]; 
NSLog(@"%@", str1); //Prints "Second!" 
+0

我還沒有嘗試過,但如何使用'replaceBytesInRange:withBytes:'但指定一個零長度範圍? – rmaddy

+0

@rmaddy我試過,但它也沒有工作。看我的編輯,以確保我知道你的意思。 – Milo

+0

我想這是行不通的。它必須查看範圍長度以知道從'withBytes:'參數獲得多少個字節。 – rmaddy

回答

5
[theData replaceBytesInRange:NSMakeRange(0, 0) withBytes:(const void *)fir length:strlen(fir)]; 

應該做的伎倆。

+0

沒有。只是取代第二!與第一! – Milo

+0

啊,在strlen中輸入了錯誤的字符串。現在它打印出「First!Second!」爲了我。 –

+0

非常感謝! – Milo