问题描述:

Ive been looking around trying to find a good tutorial on encoding a set of integers and strings, wrapping them in an array, and then Archiving it using either NSKeyed or NSUnkeyed archiver (ultimately to then put into an NSData object and transmit it over Wi-Fi).

For example I have 3 ints and 3 strings called

int1

int2

int3

string1

string2

string3

Can anyone provide me with example code, or a link to a good tutorial which contains examples on how to do this? Including the method by which I need to encode all my objects, as im still unsure on how this is achieved when also trying to wrap these encoded items into an array and then Archive them.

I've read the Archives and Serializations Programming Guide on the apple website, and its not very illuminating when put into the context of trying to wrap this all up in an array then archive it.

If I didnt need to transmit Strings too, id be tempted to just create a packet of CFSwappedFloat32's ala GKRocket, but the strings are pretty integral.

Thanks

网友答案:

Could you be a little more specific about where you're having trouble? All you need to do is to create a data object and an archiver, and then start archiving things. Call -finishEncoding when you're done.

Let's encode a some bank account information:

const NSString *AccountHolderKey = @"account_holder";
const NSString *AccountNumberKey = @"account_number";
const NSString *AccountBalanceKey = @"account_balance";

//...

NSString *accountHolder = @"Johnny Appleseed";
int accountNumber = 12345;
int balance = 1250;

NSMutableData *archivedData = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

[archiver encodeObject:accountHolder forKey:AccountHolderKey];
[archiver encodeInt:accountNumber forKey:AccountNumberKey];
[archiver encodeInt:balance forKey:AccountBalanceKey];

[archiver finishEncoding];
[archiver release];

// now you can do what you like with archivedData
相关阅读:
Top