简体   繁体   English

如何从NSMutableData对象的末尾删除字节

[英]How to remove bytes from the end of NSMutableData object

I have a NSMutableData object that is giving me some trouble, I am trying to remove the last 6 bytes from the object like this 我有一个NSMutableData对象,给我一些麻烦,我试图从这个对象中删除最后6个字节

NSMutableData *reducedDataPacket = [[NSMutableData alloc] init];
        reducedDataPacket = [myCompressedData copy];

NSRange range = NSMakeRange([reducedDataPacket length]-6, 6);
        [reducedDataPacket replaceBytesInRange:range withBytes:NULL length:0];

However once the last line executes my app crashes and I am left with this error below. 但是,一旦最后一行执行我的应用程序崩溃,我将在下面留下此错误。

-[NSConcreteData replaceBytesInRange:withBytes:length:]: unrecognized selector sent to instance 0x1f037870
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSConcreteData replaceBytesInRange:withBytes:length:]: unrecognized selector sent to instance 0x1f037870

I have never tried doing this before and have been going off other answeres supplied I have investigated, but I just cannot get this to work... any help would be greatly appreciated. 我之前从未尝试过这样做,并且已经离开了我调查过的其他回答,但是我无法让这个工作......任何帮助将不胜感激。

Your first line is useless because you then redefine reducedDataPacket in the second line, so that first line should be deleted. 您的第一行是无用的,因为您在第二行重新定义reducedDataPacket,因此应删除第一行。 I'm guessing that myCompressedData is NSData rather than NSMutableData, so change that second line to : 我猜测myCompressedData是NSData而不是NSMutableData,所以将第二行更改为:

NSMutableData *reducedDataPacket = [myCompressedData mutableCopy];

First you need a mutable instance, it isn't clear why you create one and then copy it. 首先,您需要一个可变实例,不清楚为什么要创建一个然后复制它。 You should just do: 你应该这样做:

NSMutableData *reducedDataPacket = [myCompressedData mutableCopy];

Then you want to reduce the length, not try to fill part of the data with nothing: 然后你想减少长度,而不是试图填充部分数据:

[reducedDataPacket setLength:(reducedDataPacket.length - 6)];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM