使用 NSKeyedArchiver/ NSKeyedUnarchiver 存储 NSObject
我有一个类对象,例如;
BookEntity.h
import <Cocoa/Cocoa.h>
@interface BookEntity : NSObject<NSCoding> {
NSString *name;
NSString *surname;
NSString *email;
}
@property(copy) NSString *name,*surname,*email;
@end
BookEntity.m
#import "BookEntity.h"
@implementation BookEntity
@synthesize name,surname,email;
- (void) encodeWithCoder: (NSCoder *)coder
{
[coder encodeObject: self forKey:@"appEntity"];
}
- (id) initWithCoder: (NSCoder *)coder
{
if (self = [super init])
{
self = [coder decodeObjectForKey:@"appEntity"];
}
return self;
}
和我为这个类分配了一些值,
BookEntity *entity = [[BookEntity alloc] init];
entity.name = @"Stewie";
entity.surname = @"Griffin";
entity.email = @"[email protected]";
所以我想使用 NSKeyedArchiver 存储这个类并使用 NSKeyedUnarchiver 恢复。
我写入文件,但是当我检索该文件时,该实体具有任何值。
最好的方法是什么?
谢谢。
I have a class object like;
BookEntity.h
import <Cocoa/Cocoa.h>
@interface BookEntity : NSObject<NSCoding> {
NSString *name;
NSString *surname;
NSString *email;
}
@property(copy) NSString *name,*surname,*email;
@end
BookEntity.m
#import "BookEntity.h"
@implementation BookEntity
@synthesize name,surname,email;
- (void) encodeWithCoder: (NSCoder *)coder
{
[coder encodeObject: self forKey:@"appEntity"];
}
- (id) initWithCoder: (NSCoder *)coder
{
if (self = [super init])
{
self = [coder decodeObjectForKey:@"appEntity"];
}
return self;
}
and I assign some values to this class,
BookEntity *entity = [[BookEntity alloc] init];
entity.name = @"Stewie";
entity.surname = @"Griffin";
entity.email = @"[email protected]";
so I want to store this class using NSKeyedArchiver and restore with NSKeyedUnarchiver.
I write to file but when I retrieve this file the entity has any value.
What is the best way to do this?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您对
NSCoding
协议的使用不正确。您不应该归档对象本身,而应该归档对象的属性,然后再取消归档。您将这样做:Your use of the
NSCoding
protocol is incorrect. You shouldn't be archiving the object itself, you should be archiving the properties of your object and then unarchiving them afterwards. This is how you would do it: