Tuesday, April 23, 2013

NSData dataWithBytesNoCopy example ios


dataWithBytesNoCopy :length:

Creates and returns a data object that holds length bytes from the buffer bytes.
+ (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length
Parameters
bytes
A buffer containing data for the new object. bytes must point to a memory block allocated with malloc.
length
The number of bytes to hold from bytes. This value must not exceed the length of bytes.
Return Value of [NSData dataWithBytesNoCopy]
A data object that holds length bytes from the buffer bytes. Returns nil if the data object could not be created.
Discussion of [NSData dataWithBytesNoCopy]
The returned object takes ownership of the bytes pointer and frees it on deallocation. Therefore, bytes must point to a memory block allocated with malloc.
Example of [NSData dataWithBytesNoCopy]

+ (NSData*)AES128DecryptWithKey:(NSData*) data key:(NSData*)key {

    NSUInteger dataLength = [data length];
    NSLog(@"trying to decrypt >> %@ with key >> %@", data, key );

    size_t bufferSize           = dataLength + kCCBlockSizeAES128;
    void* buffer                = malloc(bufferSize);

    size_t numBytesDecrypted    = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                          [key bytes], kCCKeySizeAES128,
                                          NULL /* initialization vector (optional) */,
                                          [data bytes], dataLength, /* input */
                                          buffer, bufferSize, /* output */
                                          &numBytesDecrypted);
    NSLog(@"cryptstatus %d", cryptStatus);
    if (cryptStatus == kCCSuccess)
    {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }

    free(buffer); //free the buffer;
    return nil;
}