如何从iOS中存储在文件中的数据中解码多个对象

时间:2012-09-20 00:51:49

标签: iphone ios xcode ios5

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

1 个答案:

答案 0 :(得分: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扩展名呢?它只是二进制数据,对吧?