IPhoneFile OperationsNSUserDefaultsRead and WriteCustomThe object is the content to be introduced in this article.NSUserDefaultsRead and WriteCustomObject. Let's just look at the content first.NSUserDefaultsYou can access some short information, such as saving and reading a stringNSUserDefaults:
- NSString *string = [NSString stringWithString @"hahaha"];
- NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
- [ud setObject:string forKey:@"myKey"];
- NSString *value;
- value = [ud objectForKey:"myKey"];
But not all things can be put in. NSUserDefaults only supports: NSString, NSNumber, NSDate, NSArray, NSDictionary.
If a custom class is saved to an NSArray and then saved to NSUserDefaults, the operation fails. If you do not believe it, try it. If you have succeeded, please let me know.
What should we do?
The method I found is to make this custom class implement the-(id) initWithCoder: (NSCoder *) coder method and-(void) encodeWithCoder: (NSCoder *) in the <NSCoding> protocol *) coder method obj-c protocol is the java interface, is the pure virtual function of C ++), and then encode the custom Class Object To NSData, then read from NSUserDefaults.
Suppose there is such a simple Class Object
- @interface BusinessCard : NSObject <NSCoding>{
- NSString *_firstName;
- NSString *_lastName;
- }
- @property (nonatomic, retain) NSString *_firstName;
- @property (nonatomic, retain) NSString *_lastName;
- @end;
-
- @implementation BusinessCard
- @synthesize _firstName, _lastName;
- - (void)dealloc{
- [_firstName release];
- [_lastName release];
- [super dealloc];
- }
- - (id) initWithCoder: (NSCoder *)coder
- {
- if (self = [super init])
- {
- self._firstName = [coder decodeObjectForKey:@"_firstName"];
- self._lastName = [coder decodeObjectForKey:@"_lastName"];
- }
- return self;
- }
- - (void) encodeWithCoder: (NSCoder *)coder
- {
- [coder encodeObject:_firstName forKey:@"_firstName"];
- [coder encodeObject:_lastName forKey:@"_lastName"];
- }
- @end
Then, NSData is used as the carrier during access:
- BusinessCard *bc = [[BusinessCard alloc] init];
- NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
- NSData *udObject = [NSKeyedArchiver archivedDataWithRootObject:bc];
- [ud setObject:udObject forKey:@"myBusinessCard"];
- [bc release];
- udObject = nil;
- udObject = [ud objectForKey:@"myBusinessCard"];
- bc = [NSKeyedUnarchiver unarchiveObjectWithData:udObject] ;
The above code is intercepted by another program and has not been tested, but it means that. IfCustomFrom anotherCustomClass Object, then all Nested classes must be implemented <NSCoding>.
Summary:IPhoneFile OperationsNSUserDefaultsRead and WriteCustomThe object content has been introduced. I hope this article will help you!