NSMutableData的定义中关于数据操作的方法如下:
@interface NSMutableData (NSExtendedMutableData)
- (void)appendBytes:(const void *)bytes length:(NSUInteger)length;
- (void)appendData:(NSData *)other;
- (void)increaseLengthBy:(NSUInteger)extraLength;
- (void)replaceBytesInRange:(NSRange)range withBytes:(const void *)bytes;
- (void)resetBytesInRange:(NSRange)range;
- (void)setData:(NSData *)data;
- (void)replaceBytesInRange:(NSRange)range withBytes:(nullable const void *)replacementBytes length:(NSUInteger)replacementLength;
@end
通过观察方法名称,怎么没有删除和插入数据的操作呢???难道不支持吗? 或者利用replace可以实现delete?好吧,我们来实验一下吧。
NSData *strData = [@"testdata" dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *data = [NSMutableData data];
[data appendData:strData];
NSLog(@"data length:%ld",data.length);
// delete
[data replaceBytesInRange:NSMakeRange(0, 4) withBytes:NULL length:0];
NSLog(@"data length:%ld",data.length);
//insert
[data replaceBytesInRange:NSMakeRange(0, 0) withBytes:strData.bytes length:strData.length];
NSLog(@"data length:%ld",data.length);
输出如下:
data length:8
data length:4
data length:12
so,果然如此。原来通过replace可以实现delete和insert功能。
ps: 发现了另一种删除的方式:
NSData *payloadData = [_receiveBuffer subdataWithRange:range];
uint32_t remainLen = (int)[_receiveBuffer length] - pduLen;
range = NSMakeRange(pduLen, remainLen);
NSData *remainData = [_receiveBuffer subdataWithRange:range];
[_receiveBuffer setData:remainData];
网友评论