Saturday, August 11, 2012

NSData General

Convert NSData To String

        NSString *MyString = [[NSString alloc] initWithData:MyData encoding:NSUTF8StringEncoding];

        [MyString release];

Convert String To NSData

        NSData *data = [myString dataUsingEncoding:NSUTF8StringEncoding];


        if (data.length > 0)

Accessing Individual Bytes

        UInt8 *bytes = (UInt8 *)data.bytes;
        if (data.length >= 4)
                NSLog(@"Byte0: %d, Byte1: %d, Byte2: %d, Byte3: %d", bytes[0], bytes[1], bytes[2], bytes[3]);

Create NSData From File

        NSData *data = [NSData dataWithContentsOfFile:filePath];

Create NSData From String

        NSData *TxData = [@"Hello World" dataUsingEncoding:NSUTF8StringEncoding];

Create NSData From Byte Array

        UInt8 TxDataBytes[10];
        int TxDataIndex = 0;

        TxDataBytes[TxDataIndex++] = 0x01;
        TxDataBytes[TxDataIndex++] = 0x02;
        TxDataBytes[TxDataIndex++] = 0x03;
        TxDataBytes[TxDataIndex++] = 0x04;

        NSData *TxData = [NSData dataWithBytes:&TxDataBytes length:TxDataIndex];

Copy Data To Array

        NSMutableArray *ReceivedData = (NSMutableArray *)[data bytes];

No comments:

Post a Comment