Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use enumerateByteRangesUsingBlock in Objective-C?

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?

like image 214
htredleaf Avatar asked Dec 05 '22 04:12

htredleaf


1 Answers

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);
}
like image 72
Paulw11 Avatar answered Dec 27 '22 09:12

Paulw11