**
**
@implementation Player
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (IBAction)savePlayer:(id)sender {
NSString *path = @"/Users/username/fm.plist";
NSString *pl= [teamPlayer stringValue];
NSString *name = [namePlayer stringValue];
NSString *age = [agePlayer stringValue];
NSString *position= [positionPlayer stringValue];
Player *player = [[Player alloc] init];
array = [[NSMutableArray alloc] initWithObjects:pl,
name, age, position, nil];
[NSKeyedArchiver archiveRootObject:array toFile:path];
NSString *ns = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"test: %@" , ns);
[array release];
}
-
- (void) encodeWithCoder: (NSCoder *) coder{
[coder encodeObject:array forKey:@"someArray"];
}
- (void) decodeWithCoder: (NSCoder *) coder{
[coder decodeObjectForKey:@"someArray"];
return self;
}
答案 0 :(得分:1)
首先,最后两种方法似乎并不相关,因为您没有编码这些方法所属的对象。同样,NSCoding
协议包括encodeWithCoder:
和initWithCoder:
方法。 decodeWithCoder:
协议中没有NSCoding
方法。
其次,您正在创建一个新的NSMutableArray
对象,该对象使用少量元素初始化并将其存档到文件中,以便将其写入现有文件。您需要通过取消归档文件,创建可变副本然后附加值来获取现有数组。所以代码就是这样的,
NSArray *existingValues = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSArray *newValues = [existingValues copy];
[newValues addObjectsFromArray:[NSArray arrayWithObjects:pl, name, age, position, nil]];
[NSKeyedArchiver archiveRootObject:newValues toFile:path];
[newValues release];