Pham Hoan
Pham Hoan

Reputation: 2127

Convert multiple data types to NSData objective C

How can I convert long long (8 bytes), int (4 bytes), short (2 bytes), Byte (1 byte) and NSString to an array bytes (NSData) to send it over the Internet ?

ie, how can I convert these into bytes:

long long currentTime = [[NSDate date] timeIntervalSince1970];

int databaseVersion = [SqliteUtils getDatabaseVersion];

Byte type = 2

etc ...

Thanks.

Upvotes: 0

Views: 938

Answers (3)

Andrey Chernukha
Andrey Chernukha

Reputation: 21808

For primitive types:

int a = 10;
NSData *data = [NSData dataWithBytes:&a length:sizeof(a)];

For NSString:

NSData *data = [@"string" dataUsingEncoding:NSUTF8StringEncoding];

Upvotes: 2

Krypton
Krypton

Reputation: 3325

Probably you're looking for NSKeyedArchiver and NSKeyUnarchiver. The concept is called data serialization or marshalling. Basically it allows you to serialize an arbitary Objective-C object to get an NSData object

Upvotes: 0

Wojtek Surowka
Wojtek Surowka

Reputation: 20993

Use

[NSData dataWithBytes:&currentTime length:sizeof(currentTime)];

Upvotes: 0

Related Questions