The method enumerateByteRangesUsingBlock:
is in class NSData
, and interpreted in Apple Documentation as following:
Enumerate through each range of bytes in the data object using a block.
- (void)enumerateByteRangesUsingBlock:(void (^)(const void *bytes, NSRange byteRange, BOOL *stop))block
Parameters
block
The block to apply to byte ranges in the array.The block takes three arguments:
bytes
The bytes for the current range.byteRange
The range of the current data bytes.stop
A reference to a Boolean value. The block can set the value to YES to stop further processing of the data. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block.Discussion
The enumeration block is called once for each contiguous region of memory in the receiver (once total for a contiguous NSData object), until either all bytes have been enumerated, or the stop parameter is set to YES.
But my question is, when will the block be executed? Which method is responsible for providing arguments bytes
, byteRange
and stop
for the block? For example, if I want to traverse a part of the bytes array, what should I do to control?
The bytes
, byteRange
and stop
parameters are passed to your block by enumerateByteRangesUsingBlock
. You don't specify which bytes you want to traverse - you use this method to traverse all of the bytes (You can terminate early via stop
).
As a simple example, say you wanted to search through some NSData
looking for a 0xff. You could use -
NSInteger ffFound=NSNotFound;
[myData enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
for (NSInteger i=0;i<byteRange.length;i++) {
if (bytes[i]== 0xff) {
ffFound=byteRange.location+i;
*stop=YES;
break;
}
}
}];
if (ffFound != NSNotFound) {
NSLog(@"0xFF was found at location %ld",(long)ffFound);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With