ios - Is is safe to modify readonly NSData via pointer address? -
i want perform xor operation nsdata below, safe modify readonly nsdata (non arc)? have tried, did work.
@implementation nsdata (additions) - (void)xorwithbytekey:(byte)keybyte { char *curdataptr = (char *)self.bytes; (int x = 0; x < self.length; x++) { *curdataptr = *curdataptr ^ keybyte; curdataptr++; } } @end
from @ cfdata source code doing seems safe. had quick search references _bytes
(which accessing directly) , nothing jumped @ me.
though want take risk of relying on such implementation detail? costly in code go via nsmutabledata copy of data , modify instead?
as in category (warning, untested):
@interface nsdata (xoring) - (nsdata *) xorwithbytekey: (byte) b ; @end @implementation nsdata (xoring) - (nsdata *) xorwithbytekey: (byte) b { nsmutabledata * copy = [self mutablecopy] ; char *p = (char *)copy.bytes; (nsuinteger = 0, length = copy.length ; < length; ++i) { byte c = *p ; c ^= b ; *p++ = c ; } return copy ; }
@end
Comments
Post a Comment