Saturday, June 1, 2013

NSMutableData dataWithCapacity example in Objective C (iOS).


NSMutableData dataWithCapacity

Creates and returns an NSMutableData object capable of holding the specified number of bytes.

+ (id)dataWithCapacity:(NSUInteger)aNumItems

Parameters
aNumItems
The number of bytes the new data object can initially contain.

Return Value
A new NSMutableData object capable of holding aNumItems bytes.

Discussion of [NSMutableData dataWithCapacity]
This method doesn’t necessarily allocate the requested memory right away. Mutable data objects allocate additional memory as needed, so aNumItems simply establishes the object’s initial capacity. When it does allocate the initial memory, though, it allocates the specified amount. This method sets the length of the data object to 0.

If the capacity specified in aNumItems is greater than four memory pages in size, this method may round the amount of requested memory up to the nearest full page.

NSMutableData dataWithCapacity example.
#include 

-(NSData*)create20mbRandomNSData
{
  int twentyMb           = 20971520;
  NSMutableData* theData = [NSMutableData dataWithCapacity:twentyMb];
  for( unsigned int i = 0 ; i < twentyMb/4 ; ++i )
  {
    u_int32_t randomBits = arc4random();
    [theData appendBytes:(void*)&randomBits length:4];
  }
  return theData;
}

Example of [NSMutableData dataWithCapacity].
- (NSData *)randomDataWithBytes: (NSUInteger)length {
    NSMutableData *mutableData = [NSMutableData dataWithCapacity: length];
    for (unsigned int i = 0; i < size; i++) {
        NSInteger randomBits = arc4random();
        [mutableData appendBytes: (void *) &randomBits length: 1];
    } return mutableData;
}

NSMutableData dataWithCapacity example.
encoding:

NSMutableData * data = [NSMutableData dataWithCapacity:0];
float z = ...;
[data appendBytes:&z length:sizeof(float)];
decoding:

NSData * data = ...; // loaded from bluetooth
float z;
[data getBytes:&z length:sizeof(float)];

End of NSMutableData dataWithCapacity example article.