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.