這裡記錄下NSMutableData的使用,當我們用到socket傳送信息時,要將數據轉換成數據流。這時就用NSData
下面舉個小例子,說明NSData的用法。
NSMutableData *mutableData = [[NSMutableData alloc] init]; int i = 143; NSData *data = [NSData dataWithBytes:&i length:sizeof(i)]; [mutableData appendData:data]; NSString *str = @隨便寫的什麼呢?; NSData *data3 = [str dataUsingEncoding:NSUTF8StringEncoding]; NSUInteger strlen = data3.length; NSData *data6 = [NSData dataWithBytes:&strlen length:sizeof(int)]; [mutableData appendData:data6]; [mutableData appendData:data3]; int strlen1 = 0; [mutableData getBytes:&strlen1 range:NSMakeRange(4, sizeof(int))]; NSData *strData = [mutableData subdataWithRange:NSMakeRange(8, strlen1)];; NSString *string1 = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding]; NSLog(@%@,string1);