How to use enumerateByteRangesUsingBlock in Objective-C?

The method enumerateByteRangesUsingBlock:is in the class NSDataand is interpreted in the Apple Documentation as follows:

Enumerate each range of bytes in the data object using a block.
- (void)enumerateByteRangesUsingBlock:(void (^)(const void *bytes, NSRange byteRange, BOOL *stop))block

Parameters

block
A block applied to byte ranges in an array.

A block takes three arguments:
  bytes
  Bytes for the current range.
  byteRange
  The range of current bytes of data.
  stop
  A reference to a boolean value. The block can set the value to YES to stop further data processing. The stop argument is an out-only argument. You should only set the Boolean value to YES in the block.

Discussion

( NSData) , YES.

: ? bytes, byteRange stop ? , , , ?

+4
3

bytes, byteRange stop enumerateByteRangesUsingBlock. , - ( stop).

, NSData, 0xff. -

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);
}
+7

[NSData enumerateByteRangesUsingBlock:] , , , , .

, block ( , ), bytes .

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://httpbin.org/image/png"]];

[data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
    NSLog(@"You get the chunk in range: %@", NSStringFromRange(byteRange));
}];

;

NSUInteger length = [data length];
NSUInteger chunkSize = 1024;
NSUInteger chunkOffset = 0;

do {
    NSUInteger chunkSize = MIN(length - chunkOffset, chunkSize);

    NSData *chunk = [data subdataWithRange:NSMakeRange(chunkOffset, chunkSize)];
    chunkOffset = chunkOffset + chunkSize;

} while (chunkOffset < length);
+4

, :

?

, , -enumerateByteRangesUsingBlock: .

, , , . , ( ) .

-enumerateByteRangesUsingBlock: . . , .

+4

All Articles