Saturday, June 1, 2013

NSData subdataWithRange example in Objective C (iOS).


NSData subdataWithRange

Returns a data object containing the receiver’s bytes that fall within the limits specified by a given range.

- (NSData *)subdataWithRange:(NSRange)range

Parameters
range
The range in the receiver from which to get the data. The range must not exceed the bounds of the receiver.

Return Value of [NSData subdataWithRange]
A data object containing the receiver’s bytes that fall within the limits specified by range. If range isn’t within the receiver’s range of bytes, raises NSRangeException.

Discussion of [NSData subdataWithRange]
A sample using this method can be found in “Working With Binary Data”.

NSData subdataWithRange example.
while([outData length] + ptr[currentPacket].mDataByteSize < inBytesToGet && currentPacket < packetsCount)
{
NSLog(@" ++> %d", [aData retainCount]) ;
NSInteger sO = ptr[currentPacket].mStartOffset ;
NSInteger dS = ptr[currentPacket].mDataByteSize ;
NSLog(@"     get: cP: %d tP: %d mStartOffset: %d mDataByteSize: %d", currentPacket, packetsCount, sO, dS) ;
NSData *copyRange = [aData subdataWithRange: NSMakeRange(sO,dS)] ;
NSLog(@" => %d", [aData retainCount]) ;
[outData appendData:copyRange] ;
ptr[currentPacket].mStartOffset = bytesFilled + inOffset ;
[outPackets appendBytes: &ptr[currentPacket] length: sizeof(AudioStreamPacketDescription)] ;
currentPacket++ ;
bytesFilled += dS ;
}

Example of [NSData subdataWithRange].
// original data in myData
NSData *d1 = [myData subdataWithRange:NSMakeRange(0, 20)];
NSData *d2 = [myData subdataWithRange:NSMakeRange(20, 80)];

NSData subdataWithRange example.
    // Stick our chunk in the clipboard

    NSMutableArray *items = [NSMutableArray arrayWithCapacity:1];
    NSRange curRange;

    curRange.location = 0;
    curRange.length = sz;
    NSData *subData = [dataFile subdataWithRange:curRange];
    NSDictionary *dict = [NSDictionary dictionaryWithObject:subData
forKey:(NSString *)kUTTypeAudio];
    [items addObject:dict];

End of NSData subdataWithRange example article.