这是一个自定义对象转换为 NSData 的示例(因此可以将其保存为用户默认值)
创建以下文件:
目录.h
@interface Catalog : NSObject
@property (nonatomic, assign) int pk;
@property (nonatomic, copy) NSString *catalogName;
@property (nonatomic, copy) NSString *catalogDescription;
@property (nonatomic, assign) int catalogEdition;
@property (nonatomic, assign) int catalogTotalPages;
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder;
@end
目录.m
#import <Foundation/Foundation.h>
#import "Catalog.h"
@implementation Catalog
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.catalogName forKey:@"catalogName"];
[aCoder encodeObject:self.catalogDescription forKey:@"catalogDescription"];
[aCoder encodeInt:self.catalogEdition forKey:@"catalogEdition"];
[aCoder encodeInt:self.catalogTotalPages forKey:@"catalogTotalPages"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init]) {
self.catalogName = [aDecoder decodeObjectForKey:@"catalogName"];
self.catalogDescription = [aDecoder decodeObjectForKey:@"catalogDescription"];
self.catalogEdition = [aDecoder decodeIntForKey:@"catalogEdition"];
self.catalogTotalPages = [aDecoder decodeIntForKey:@"catalogTotalPages"];
}
return self;
}
@end
最后在你的控制器中包含头文件
#import "Catalog.h"
并添加此代码以使用您的对象(在这种情况下,我保存到用户默认值中)
Catalog *catalog = [[Catalog alloc] init];
catalog.catalogName = @"catalogName";
catalog.catalogDescription = @"catalogName";
catalog.catalogEdition = 1;
注意:在这行代码中是实际数据传递发生的地方
//archiving object to nsdata
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:catalog];
[[NSUserDefaults standardUserDefaults] setObject:encodedObject forKey:@"keyName"];
[[NSUserDefaults standardUserDefaults] synchronize];
如果你想从 NSData 取回你的对象
NSData *nsData = [[NSUserDefaults standardUserDefaults] objectForKey:@"keyName"];
//unarchiving object to nsdata
Catalog *selectedCatalog = [NSKeyedUnarchiver unarchiveObjectWithData: nsData];
希望这会有所帮助!