0

我有一个包含名字和姓氏以及其他一些信息的表格。我使用一个人类来存储这些信息。在提交单击时,我使用在 person 类中实现的 NSCoding 将其归档在文件 person.txt 中。如果我在文件 person.txt 中添加多个人员,我怎样才能获取文件中存储的所有人员对象。解码人员类只是给了我最后添加的人。

4

1 回答 1

1

如果您希望将所有人员对象序列化,那么您需要将NSArray存储它们的集合类或任何其他集合类作为NSKeyedArchiver. 例如:(假设为 ARC)

#import <Foundation/Foundation.h>

@interface Person:NSObject <NSCoding>
@property (nonatomic, copy) NSString *lastName;
@property (nonatomic, copy) NSString *firstName;
// etc.
@end

@implementation Person

@synthesize lastName = _lastName;
@synthesize firstName = _firstName;

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.lastName forKey:@"ln"];
    [aCoder encodeObject:self.firstName forKey:@"fn"];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if( !self ) { return nil; }

    _lastName = [aDecoder decodeObjectForKey:@"ln"];
    _firstName = [aDecoder decodeObjectForKey:@"fn"];

    return self;
}

@end

int main(int argc, char *argv[]) {
    NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];

    Person *me = [Person new];
    me.lastName = @"Kitten";
    me.firstName = @"Mittens";

    Person *you = [Person new];
    you.lastName = @"Youe";
    you.firstName = @"JoJo";

    NSArray *people = [NSArray arrayWithObjects:me,you,nil];
    NSData *serializedData = [NSKeyedArchiver archivedDataWithRootObject:people];

    //  write your serializedData to file, etc.

    [p release];
}

但是,为什么存档中的 .txt 扩展名?它只是二进制数据,对吧?

于 2012-09-20T01:44:02.667 回答