简体   繁体   中英

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.

For primitive types:

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

For NSString :

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

采用

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM