Val Nolav
Val Nolav

Reputation: 902

NSKeyedArchiver .plist appending problem

**

  1. I am getting data from a form into an array and trying to write that array into a .plist file using NSKeyedArchiver.
  2. Writing is successful,however it overwrites to the previous data whenever I run the script.
  3. 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;
}

Upvotes: 0

Views: 1386

Answers (1)

Deepak Danduprolu
Deepak Danduprolu

Reputation: 44633

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 includes encodeWithCoder: and initWithCoder: methods. There is no decodeWithCoder: method in the NSCoding 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,

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];

Upvotes: 1

Related Questions