**
- I am getting data from a form into an array and trying to write that array into a .plist file using NSKeyedArchiver.
- Writing is successful,however it overwrites to the previous data whenever I run the script.
- How can I append the new data to .plist file instead of overwriting?
**
@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;
}
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
NSCodingprotocol includesencodeWithCoder:andinitWithCoder:methods. There is nodecodeWithCoder:method in theNSCodingprotocol.Secondly, you are creating a new
NSMutableArrayobject 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,