Search code examples
objective-cxcodensdatansrangensmutabledata

NSData subdataWithRange crashing


I have the following code and I am getting an exception with it.

-[_NSInlineData replaceBytesInRange:withBytes:]: unrecognized selector sent to instance 0x6000027ff2e0' terminating with uncaught exception of type NSException

Can someone point out the issue with this?

NSMutableData *data = [[NSMutableData alloc] 
initWithLength:1000];

NSMutableData *d1 =(NSMutableData *) [data 
subdataWithRange:NSMakeRange(sizeof(uint8_t),10)];
uint8_t i = 10;
[d1 replaceBytesInRange: NSMakeRange(1, sizeof(uint8_t) 
withBytes:&i];

Solution

  • subdataWithRange: returns an immutable NSData instance. It's a copy of the original data. If you want to replace data in that copy, without affecting your original data object, you can do:

    NSData *tmp = [data subdataWithRange:NSMakeRange(sizeof(uint8_t),10)];
    NSMutableData *d1 = [tmp mutableCopy];
    

    If you want to modify the mutable data object instead, do so directly by calculating the correct range:

    // Offset derived from your example code, lines 5 and 7.
    NSUInteger offset = sizeof(uint8_t) + 1;
    NSRange range = NSMakeRange(offset, sizeof(uint8_t));
    [data replaceBytesInRange:range withBytes:&i];