Showing posts with label NSMutableData example. Show all posts
Showing posts with label NSMutableData example. Show all posts

Sunday, June 2, 2013

NSMutableData resetBytesInRange example in Objective C (iOS).


NSMutableData resetBytesInRange

Replaces with zeroes the contents of the receiver in a given range.

- (void)resetBytesInRange:(NSRange)range

Parameters
range
The range within the contents of the receiver to be replaced by zeros. The range must not exceed the bounds of the receiver.

Discussion of [NSMutableData resetBytesInRange]
If the location of range isn’t within the receiver’s range of bytes, an NSRangeException is raised. The receiver is resized to accommodate the new bytes, if necessary.

NSMutableData resetBytesInRange example.
NSMutableData *imgData = [NSMutableData data]; /* note, we do not specify a capacity--it's pointless for this use case */
[imgData setData: UIImageJPEGRepresentation(img, 1.0)];
[imgData resetBytesInRange: NSMakeRange(0, [imgData length])];
Or:

NSMutableData *imgData = [[UIImageJPEGRepresentation(img, 1.0) mutableCopy] autorelease];
[imgData resetBytesInRange: NSMakeRange(0, [imgData length])];

Example of [NSMutableData resetBytesInRange].
NSMutableData *postData = [[NSMutableData alloc] init];    [postData resetBytesInRange:NSMakeRange(0, [postData length])];
    [postData setLength:0];

NSMutableData *orgData = [[NSMutableData alloc] init];
    [orgData resetBytesInRange:NSMakeRange(0, [orgData length])];
    [orgData setLength:0];

    orgData = (NSMutableData *)[userInfo dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"-------postData------");
    CFShow(orgData);
    [postData appendBytes:[orgData bytes] length:100];
    CFShow(postData);
    return postData;

End of NSMutableData resetBytesInRange example article.

NSMutableData replaceBytesInRange withBytes example in Objective C (iOS).


NSMutableData replaceBytesInRange withBytes

Replaces with a given set of bytes a given range within the contents of the receiver.

- (void)replaceBytesInRange:(NSRange)range withBytes:(const void *)bytes

Parameters
range
The range within the receiver's contents to replace with bytes. The range must not exceed the bounds of the receiver.
bytes
The data to insert into the receiver's contents.

Discussion of [NSMutableData replaceBytesInRange withBytes]
If the location of range isn’t within the receiver’s range of bytes, an NSRangeException is raised. The receiver is resized to accommodate the new bytes, if necessary.

A sample using this method is given in Working With Mutable Binary Data.

NSMutableData replaceBytesInRange withBytes example.
[source setLength:myStart + myLength];
[source replaceBytesInRange:NSMakeRange(0, myStart)
                  withBytes:NULL
                     length:0];

Example of [NSMutableData replaceBytesInRange withBytes].
I think you want to do something like this:

[soundFileData replaceBytesInRange:NSMakeRange(4, 4)
                         withBytes:&(UInt32){NSSwapHostIntToLittle(totalLength-8)}];
[soundFileData replaceBytesInRange:NSMakeRange(42, 4)
                         withBytes:&(UInt32){NSSwapHostIntToLittle(totalLength)}];

NSMutableData replaceBytesInRange withBytes example.
    NSRange range = NSMakeRange(0, 1);
[requestData replaceBytesInRange:range withBytes:NULL length:0];

End of NSMutableData replaceBytesInRange withBytes example article.

NSMutableData replaceBytesInRange example in Objective C (iOS).


NSMutableData replaceBytesInRange

Replaces with a given set of bytes a given range within the contents of the receiver.

- (void)replaceBytesInRange:(NSRange)range withBytes:(const void *)bytes

Parameters
range
The range within the receiver's contents to replace with bytes. The range must not exceed the bounds of the receiver.
bytes
The data to insert into the receiver's contents.

Discussion of [NSMutableData replaceBytesInRange]
If the location of range isn’t within the receiver’s range of bytes, an NSRangeException is raised. The receiver is resized to accommodate the new bytes, if necessary.

A sample using this method is given in Working With Mutable Binary Data.

NSMutableData replaceBytesInRange example.
[source setLength:myStart + myLength];
[source replaceBytesInRange:NSMakeRange(0, myStart)
                  withBytes:NULL
                     length:0];

Example of [NSMutableData replaceBytesInRange].
I think you want to do something like this:

[soundFileData replaceBytesInRange:NSMakeRange(4, 4)
                         withBytes:&(UInt32){NSSwapHostIntToLittle(totalLength-8)}];
[soundFileData replaceBytesInRange:NSMakeRange(42, 4)
                         withBytes:&(UInt32){NSSwapHostIntToLittle(totalLength)}];

NSMutableData replaceBytesInRange example.
    NSRange range = NSMakeRange(0, 1);
[requestData replaceBytesInRange:range withBytes:NULL length:0];

End of NSMutableData replaceBytesInRange example article.

NSMutableData mutableBytes example in Objective C (iOS).


NSMutableData mutableBytes

Returns a pointer to the receiver’s data.

- (void *)mutableBytes

Return Value
A pointer to the receiver’s data.

Discussion of [NSMutableData mutableBytes]
If the length of the receiver’s data is not zero, this function is guaranteed to return a pointer to the object's internal bytes. If the length of receiver’s data is zero, this function may or may not return NULL dependent upon many factors related to how the object was created (moreover, in this case the method result might change between different releases).

A sample using this method can be found in Working With Mutable Binary Data.

NSMutableData mutableBytes example.
NSMutableData* mydata = [[NSMutableData alloc] init];
[mydata appendData: [@"hello" dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"%p", [mydata mutableBytes]);
NSLog(@"%p", [mydata bytes]);

Example of [NSMutableData mutableBytes].
typedef struct {
    UInt32      riffChunkID; // Always RIFF, in big endian. Integer fields are little-ending.
    UInt32      fileLength;
    UInt32      waveFileID; // 'WAVE' for Wave files.
    UInt32      formatChunkID; // 'fmt '
    UInt32      formatChunkSize;
    SInt16      formatTag; // Wave Format ID: see constants
    SInt16      channels; // Number of Channels: 1=mono, 2=stereo
    SInt32      sampleRate; // Sample Rate: samples per second
    SInt32      bytesPerSec; // sampleRate * blockAlign
    SInt16      blockAlign; // sample frame size = channels * sampleSize / 8
    SInt16      bitsPerSample; // sampleSize (8 or 16), also two's-complement for 16-bit, offset for 8-bit
    UInt32      dataChunkID;  // 'data'
    UInt32      dataChunkSize;
} WaveHeader;

int tfChannels = 1; // mono
int tfSampleRate = 44100;
int tfBitsPerSample = 16;

WaveHeader *header = [maindata mutableBytes];

header->riffChunkID = CFSwapInt32HostToBig ('RIFF');
header->fileLength = CFSwapInt32HostToLittle ([maindata length] - 8);
header->waveFileID = CFSwapInt32HostToBig ('WAVE');

header->formatChunkID = CFSwapInt32HostToBig ('fmt ');
header->formatChunkSize = CFSwapInt32HostToLittle (16);
header->formatTag = CFSwapInt16HostToLittle (1);
header->channels = CFSwapInt16HostToLittle (tfChannels);
header->sampleRate = CFSwapInt32HostToLittle (tfSampleRate);
header->bytesPerSec = CFSwapInt32HostToLittle (tfSampleRate * tfBitsPerSample / 8 * tfChannels);
header->blockAlign = CFSwapInt16HostToLittle (tfBitsPerSample / 8 * tfChannels);
header->bitsPerSample = CFSwapInt16HostToLittle (tfBitsPerSample);
header->dataChunkID = CFSwapInt32HostToBig ('data');
header->dataChunkSize = CFSwapInt32HostToLittle ([maindata length] - 44);

NSMutableData mutableBytes example.
NSMutableData* mutableData = [NSMutableData dataWithLength: someLength];
void* bitmapData = [mutableData mutableBytes];
CGContextRef context = CGBitmapContextCreate(bitmapData,...);
// ...use context
CGContextRelease(context);

End of NSMutableData mutableBytes example article.

Saturday, June 1, 2013

NSMutableData initWithLength example in Objective C (iOS).


NSMutableData initWithLength

Initializes and returns an NSMutableData object containing a given number of zeroed bytes.

- (id)initWithLength:(NSUInteger)length

Parameters
length
The number of bytes the object initially contains.

Return Value of [NSMutableData initWithLength]
An initialized NSMutableData object containing length zeroed bytes.

NSMutableData initWithLength example.
-(NSMutableData*) bar
{
    return [[[NSMutableData alloc] initWithLength:100] autorelease];
}

Example of [NSMutableData initWithLength].
 NSUInteger length = [[invocation methodSignature] methodReturnLength];
if(length!=0){
    NSMutableData * dat = [[NSMutableData alloc] initWithLength:length];
    void* returnBuffer =  [dat mutableBytes];
    [invocation getReturnValue:&returnBuffer];
    void(^delayedFree)(void) = ^{ [dat release]; };
    [[NSOperationQueue mainQueue] addOperationWithBlock:delayedFree];
    return returnBuffer;
}
return nil;

NSMutableData initWithLength example.
- (NSMutableData *)dataToBeLoaded;
{
    if (!_dataToBeLoaded) {
        _dataToBeLoaded = [[NSMutableData alloc] initWithLength:1000];
    }
    return _dataToBeLoaded;
}

End of NSMutableData initWithLength example article.

NSMutableData initWithCapacity example in Objective C (iOS).


NSMutableData initWithCapacity

Returns an initialized NSMutableData object capable of holding the specified number of bytes.

- (id)initWithCapacity:(NSUInteger)capacity

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

Return Value
An initialized NSMutableData object capable of holding capacity bytes.

Discussion of [NSMutableData initWithCapacity]
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 initWithCapacity example.
self.receiveData = [[[NSMutableData alloc] initWithCapacity:0] autorelease];
OR

 NSMutableData * myData =  [[NSMutableData alloc] initWithCapacity:0];
   self.receiveData = myData ;
   [myData release];
    myData  = nil ;

Example of [NSMutableData initWithCapacity].

-(void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {

    if (data==nil) {

        data = [[NSMutableData alloc] initWithCapacity:2048];

    }

    [data appendData:incrementalData];

}

NSMutableData initWithCapacity example.
-(void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {
    if (data==nil) { data = [[NSMutableData alloc] initWithCapacity:2048]; }
    [data appendData:incrementalData];
}

End of NSMutableData initWithCapacity example article.

NSMutableData increaseLengthBy example in Objective C (iOS).


NSMutableData increaseLengthBy

Increases the length of the receiver by a given number of bytes.

- (void)increaseLengthBy:(NSUInteger)extraLength

Parameters
extraLength
The number of bytes by which to increase the receiver's length.

Discussion of [NSMutableData increaseLengthBy]
The additional bytes are all set to 0.

NSMutableData increaseLengthBy example.
ou want to use an NSMutableData, which you make from the NSData you get back from the string, then add some zeros:

NSMutableData paddedData = [NSMutableData dataWithData:d];
[paddedData increaseLengthBy:4];

Example of [NSMutableData increaseLengthBy].
NSData* compressData(NSData* uncompressedData) {
if ([uncompressedData length] == 0) return uncompressedData;

z_stream strm;

strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.total_out = 0;
strm.next_in=(Bytef *)[uncompressedData bytes];
strm.avail_in = (unsigned int)[uncompressedData length];

// Compresssion Levels:
//   Z_NO_COMPRESSION
//   Z_BEST_SPEED
//   Z_BEST_COMPRESSION
//   Z_DEFAULT_COMPRESSION

if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15+16), 8, Z_DEFAULT_STRATEGY) != Z_OK) return nil;

NSMutableData *compressed = [NSMutableData dataWithLength:16384];  // 16K chunks for expansion

do {

    if (strm.total_out >= [compressed length])
        [compressed increaseLengthBy: 16384];

    strm.next_out = [compressed mutableBytes] + strm.total_out;
    strm.avail_out = (unsigned int)([compressed length] - strm.total_out);

    deflate(&strm, Z_FINISH); 

} while (strm.avail_out == 0);

deflateEnd(&strm);

[compressed setLength: strm.total_out];
return [NSData dataWithData:compressed];
}

NSMutableData increaseLengthBy example.
if ([compressedData length] == 0) return compressedData;

NSUInteger full_length = [compressedData length];
NSUInteger half_length = [compressedData length] / 2;

NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length];
BOOL done = NO;
int status;

z_stream strm;
strm.next_in = (Bytef *)[compressedData bytes];
strm.avail_in = (unsigned int)[compressedData length];
strm.total_out = 0;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;

if (inflateInit2(&strm, (15+32)) != Z_OK) return nil;

while (!done) {
    // Make sure we have enough room and reset the lengths.
    if (strm.total_out >= [decompressed length]) {
        [decompressed increaseLengthBy: half_length];
    }
    strm.next_out = [decompressed mutableBytes] + strm.total_out;
    strm.avail_out = (unsigned int)([decompressed length] - strm.total_out);

    // Inflate another chunk.
    status = inflate (&strm, Z_SYNC_FLUSH);
    if (status == Z_STREAM_END) {
        done = YES;
    } else if (status != Z_OK) {
        break;
    }
}
if (inflateEnd (&strm) != Z_OK) return nil;

// Set real length.
if (done) {
    [decompressed setLength: strm.total_out];
    return [NSData dataWithData: decompressed];
} else {
    return nil;
}
}

End of NSMutableData increaseLengthBy example article.

NSMutableData appendData example in Objective C (iOS).


NSMutableData appendData

Appends the content of another NSData object to the receiver.

- (void)appendData:(NSData *)otherData

Parameters of [NSMutableData appendData]
otherData
The data object whose content is to be appended to the contents of the receiver.

NSMutableData appendData example.
self.globalData = [[NSMutableData alloc] init];

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.globalData appendData:data];
    float progress = (float)[self.globalData length] / self.downloadSize;
    self.threadProgressView.progress = progress;
}

Example of [NSMutableData appendData].
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if(!receivedData)
    {
        receivedData = [NSMutableData data];
    }
    [receivedData appendData:data];
}

NSMutableData appendData example.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
  NSMutableData *currentData = (NSMutableData*)[receivedData objectForKey:[connection description]];
  [currentData.appendData:data];
}

End of NSMutableData appendData example article.

NSMutableData appendBytes length example in Objective C (iOS).


NSMutableData appendBytes length

Appends to the receiver a given number of bytes from a given buffer.

- (void)appendBytes:(const void *)bytes length:(NSUInteger)length

Parameters
bytes
A buffer containing data to append to the receiver's content.
length
The number of bytes from bytes to append.

Discussion of [NSMutableData appendBytes length]
A sample using this method can be found in Working With Mutable Binary Data.

NSMutableData appendBytes length example.
For example, to convert from host (your machine) to network endianness, use htonl():

uint32_t theInt = htonl((uint32_t)myInteger);
[myData appendBytes:&theInt length:sizeof(theInt)];

Example of [NSMutableData appendBytes length].
NSMutableData *data = [NSMutableData data];
char bytesToAppend[5] = {0x01, 0xf0, 0x64, 0x0, 0x6a};
[data appendBytes:bytesToAppend length:sizeof(bytesToAppend)];

NSMutableData appendBytes length example.
To store:

SInt16 *frames = ...;
NSUInteger length = ...;    // Assuming number of elements in frames, not bytes!  
NSMutableData *data = [[NSMutableData alloc] initWithCapacity:0];
[data appendBytes:(const void *)frames length:length * sizeof(SInt16)];
To retrieve:

SInt16 *frames = (SInt16 *)[data bytes];
NSUInteger length = [data length] / sizeof(SInt16);

End of NSMutableData appendBytes length example article.

NSMutableData appendBytes example in Objective C (iOS).


NSMutableData appendBytes

Appends to the receiver a given number of bytes from a given buffer.

- (void)appendBytes:(const void *)bytes length:(NSUInteger)length

Parameters
bytes
A buffer containing data to append to the receiver's content.
length
The number of bytes from bytes to append.

Discussion of [NSMutableData appendBytes]
A sample using this method can be found in Working With Mutable Binary Data.

NSMutableData appendBytes example.
For example, to convert from host (your machine) to network endianness, use htonl():

uint32_t theInt = htonl((uint32_t)myInteger);
[myData appendBytes:&theInt length:sizeof(theInt)];

Example of [NSMutableData appendBytes].
NSMutableData *data = [NSMutableData data];
char bytesToAppend[5] = {0x01, 0xf0, 0x64, 0x0, 0x6a};
[data appendBytes:bytesToAppend length:sizeof(bytesToAppend)];

NSMutableData appendBytes example.
To store:

SInt16 *frames = ...;
NSUInteger length = ...;    // Assuming number of elements in frames, not bytes!  
NSMutableData *data = [[NSMutableData alloc] initWithCapacity:0];
[data appendBytes:(const void *)frames length:length * sizeof(SInt16)];
To retrieve:

SInt16 *frames = (SInt16 *)[data bytes];
NSUInteger length = [data length] / sizeof(SInt16);

End of NSMutableData appendBytes example article.

NSMutableData dataWithLength example in Objective C (iOS).


NSMutableData dataWithLength

Creates and returns an NSMutableData object containing a given number of zeroed bytes.

+ (id)dataWithLength:(NSUInteger)length

Parameters
length
The number of bytes the new data object initially contains.

Return Value of [NSMutableData dataWithLength]
A new NSMutableData object of length bytes, filled with zeros.

NSMutableData dataWithLength example.
 long long length = 1024ull * 1024ull * 1024ull * 2ull; // 2 GB

 db = [NSMutableData dataWithLength:length];

 char *array = [db mutableBytes];

 for(long long i = 0; i < length - 1; i++) {
      array[i] = i % 256;
 }

Example of [NSMutableData dataWithLength].
NSMutableData* mutableData = [NSMutableData dataWithLength: someLength];
void* bitmapData = [mutableData mutableBytes];
CGContextRef context = CGBitmapContextCreate(bitmapData,...);
// ...use context
CGContextRelease(context);

NSMutableData dataWithLength example.
- (NSData *)gzipInflate:(NSData*)data
{
    if ([data length] == 0) return data;

    unsigned full_length = [data length];
    unsigned half_length = [data length] / 2;

    NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length];
    BOOL done = NO;
    int status;

    z_stream strm;
    strm.next_in = (Bytef *)[data bytes];
    strm.avail_in = [data length];
    strm.total_out = 0;
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;

    if (inflateInit2(&strm, (15+32)) != Z_OK) return nil;
    while (!done)
    {
        // Make sure we have enough room and reset the lengths.
        if (strm.total_out >= [decompressed length])
            [decompressed increaseLengthBy: half_length];
        strm.next_out = [decompressed mutableBytes] + strm.total_out;
        strm.avail_out = [decompressed length] - strm.total_out;

        // Inflate another chunk.
        status = inflate (&strm, Z_SYNC_FLUSH);
        if (status == Z_STREAM_END) done = YES;
        else if (status != Z_OK) break;
    }
    if (inflateEnd (&strm) != Z_OK) return nil;

    // Set real length.
    if (done)
    {
        [decompressed setLength: strm.total_out];
        return [NSData dataWithData: decompressed];
    }
    else return nil;
}

End of NSMutableData dataWithLength example article.

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.