Thursday, May 2, 2013

NSKeyedArchiver initForWritingWithMutableData example ios


Returns the receiver, initialized for encoding an archive into a given a mutable-data object.
- (id)initForWritingWithMutableData:(NSMutableData *)data
The mutable-data object into which the archive is written.
Return Value of [NSKeyedArchiver initForWritingWithMutableData]
The receiver, initialized for encoding an archive into data.
When you finish encoding data, you must invoke finishEncoding at which point data is filled. The format of the receiver is NSPropertyListBinaryFormat_v1_0.
Example of [NSKeyedArchiver initForWritingWithMutableData]
NSMutableData *data = [[NSMutableData alloc]init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:YOURDICTIONARY forKey: YOURDATAKEY];
archiver finishEncoding];
[data writeToFile:YOURFILEPATH atomically:YES];
[data release];
[archiver release];
Example of [NSKeyedArchiver initForWritingWithMutableData]
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