-
(IBAction)write:(id)sender
{
//
get document path
NSArray
*
paths
=
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString
*
documentsDirectory
=
[paths objectAtIndex:
0
];
NSString
*
filePath
=
[documentsDirectory stringByAppendingPathComponent:k_FILE_NAME];
NSMutableData
*
data
=
[[[NSMutableData alloc] init] autorelease];
NSKeyedArchiver
*
archiver
=
[[[NSKeyedArchiver alloc] initForWritingWithMutableData:data] autorelease];
UserEntity
*
userEntity
=
[[[UserEntity alloc] init] autorelease];
userEntity.age
=
18
;
userEntity.gender
=
NO;
userEntity.userName
=
@"
add
"
;
NSArray
*
friends
=
[[NSArray alloc] initWithObjects:
@"
ac
"
,
@"
2
"
,
@"
3
"
,
@"
4
"
, nil];
userEntity.friends
=
friends;
AddressEntity
*
address
=
[[[AddressEntity alloc] init] autorelease];
address.Id
=
1
;
address.address
=
@"
china
"
;
userEntity.address
=
address;
AddressEntity
*
address2
=
[[[AddressEntity alloc] init] autorelease];
address2.Id
=
2
;
address2.address
=
@"
china2
"
;
AddressEntity
*
address3
=
[[[AddressEntity alloc] init] autorelease];
address3.Id
=
3
;
address3.address
=
@"
china3
"
;
NSArray
*
addresses
=
[[NSArray alloc] initWithObjects:address2, address3 , nil];
userEntity.addresses
=
addresses;
[archiver encodeObject:userEntity forKey:
@"
KEY
"
];
[archiver finishEncoding];
BOOL success
=
[data writeToFile:filePath atomically:YES];
}
-
(IBAction)read:(id)sender
{
NSArray
*
paths
=
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString
*
documentsDirectory
=
[paths objectAtIndex:
0
];
NSString
*
filePath
=
[documentsDirectory stringByAppendingPathComponent:k_FILE_NAME];
NSData
*
data
=
[[NSData alloc] initWithContentsOfFile:filePath];
NSKeyedUnarchiver
*
unArchiver
=
[[NSKeyedUnarchiver alloc] initForReadingWithData:data];
UserEntity
*
userEntity
=
[unArchiver decodeObjectForKey:
@"
KEY
"
];
NSLog(
@"
name is %@ , friend %@ address :%@ , addresses is :%@
"
, userEntity.userName , userEntity.friends , userEntity.address, userEntity.addresses);
}