In IOS apps, if you want to save big object data, you can use XML files or attribute files. However, because the plain text method is not confidential enough, for example, you can encapsulate the stored data as an instance of a custom class and save the data in a serialized binary format, which improves the security. In addition, the following articles will introduce algorithms such as RSA and MD5 to encrypt and decrypt stored data.
Classes with serialization capabilities must implement two nscoding functions:
-(void) encodeWithCoder:(NSCoder *)encoder;-(id) initWithCoder:(NSCoder *)decoder;
The encodewithcoder function serializes various data fields of the custom object, and the initwithcoder function deserializes binary data files into object instances.
For example, a website's registered user information class contains the site name sitename, site address siteaddress, registered username, Login Password, and user profile logoimage.
The data class declaration code:
#import <Foundation/Foundation.h>@interface RegUserInfo : NSObject <NSCoding> { NSString *siteName; NSString *siteAddress; NSString *userName; UIImage *logoImage;}@property (nonatomic, strong) NSString *siteName, *siteAddress, *userName;@property (nonatomic, strong) UIImage *logoImage;@end
To serialize data members, you must implement-(void) encodeobject :( ID) objv forkey :( nsstring *) key. If the data member is of the basic data type int, you must use
-(Void) encodeint :( INT) intv forkey :( nsstring *) key. The specific implementation of encodewithcoder is as follows.
-(void) encodeWithCoder:(NSCoder *)encoder {[encoder encodeObject:siteName forKey:@"siteName"];[encoder encodeObject:siteAddress forKey:@"siteAddress"];[encoder encodeObject:userName forKey:@"userName"];[encoder encodeObject:logoImage forKey:@"logoImage"];}
Note: The specified key value for serialization must be unique and the key used during encoding and decoding must be consistent.
The serialization and deserialization code for the userinfo object is as follows.
/* Serialize to arch. DAT file */[nskeyedarchiver archiverootobject: userinfo tofile: @ "arch. dat "];/* by the file arch. dat deserialization to reguserinfo object */reguserinfo * newuserinfo = [nskeyedunarchiver unarchiveobjectwithfile: @ "arch. dat "];
Post: http://blog.csdn.net/hsyj_0001/article/details/7594642