NSKeyedArchiver .plist 附加问题
**
- 我正在将数据从表单获取到数组中,并尝试使用 NSKeyedArchiver 将该数组写入 .plist 文件。
- 写入成功,但是每当我运行脚本时它都会覆盖以前的数据。
- 如何将新数据附加到 .plist 文件而不是覆盖?
**
@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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,最后两个方法似乎不相关,因为您没有对这些方法所属的对象进行编码。同样,
NSCoding
协议包含encodeWithCoder:
和initWithCoder:
方法。NSCoding
协议中没有decodeWithCoder:
方法。其次,您将创建一个新的 NSMutableArray 对象,该对象用几个元素进行初始化,并将其归档到一个文件中,以便它覆盖现有的对象。您需要通过取消归档文件来获取现有数组,创建可变副本,然后附加值。所以代码会是这样的,
First of all, the last two methods don't seem to be relevant as you aren't encoding whichever object those methods belong to. Again, the
NSCoding
protocol includesencodeWithCoder:
andinitWithCoder:
methods. There is nodecodeWithCoder:
method in theNSCoding
protocol.Secondly, you are creating a new
NSMutableArray
object initialized with few elements and archiving it to a file so it writes over the existing one. You will need to get the existing array through unarchiving the file, create a mutable copy and then appending the values. So code will be something like this,