Blane Townsend
Blane Townsend

Reputation: 3038

Can I have 2 arrays within a plist?

I am trying to save data for an iphone app that I am building. My data structure is to save a gamesArray that contains individual gameArray. In each gameArray I have a date, name, home/away, and a shotArray. The shotArray contains the shots. The shots when loaded create UIButtons to display on the screen. The shotButtonArray contains these buttons. When I view my file in the plist editor I don't see distinct arrays. I only see 1 array and all of the created objects are just listed. Why does it only show one array. Here is how I am saving my data

for (UIButton *button in shotButtonArray) {

        assert([button isKindOfClass:[UIButton class]]);
        [button removeFromSuperview];
    }
    for (Shot *shot in shotArray) {
        [shot subtract_miss_And_make];
    }
    [self reDrawShots];
    [shotButtonArray removeAllObjects];
    [shotArray removeAllObjects];
    [gameArray removeAllObjects];
    [gameArray addObject:theDate];
    [gameArray addObject:theName];
    NSNumber *theNumber = [NSNumber numberWithInt:homeAway];
    [gameArray addObject:theNumber];
    [gameArray addObject:shotArray];
    gameNumber = 0;
    [gamesArray addObject:gameArray];
    NSString *path = [self findGamesPath];
    [NSKeyedArchiver archiveRootObject:gamesArray toFile:path];

Am I saving my data incorrectly. Why does it show only one array.

Upvotes: 1

Views: 239

Answers (1)

drewag
drewag

Reputation: 94723

There is nothing technically wrong with the way you are saving it. I am confused though; why are you removing all the objects from shotArray before saving it to the gameArray? Also, why are you storing only one gameArray within the gamesArray?

Even though there is nothing wrong with the way you are saving this, I will suggest a better way to do this. You should create a new class that represents a "game". This can save the attributes you want like the date, name, number, etc. using keys and values. If you override the -(void)encodeWithCoder:(NSCoder*)coder function in that class you can call:

[coder encodeObject:theData forKey:@"DATE"];
[coder encodeInteger:theNumber forKey:@"NUMBER"];

Then, when you override - (void)encodeWithCoder:(NSCoder *)encoder you can access that value be calling:

theDate = [[coder decodeObjectForKey:@"DATE"] retain];
theNumber = [coder decodeObjectForKey:@"NUMBER"];

This way, you can just create an array of these objects, ask NSKeyedArchiver to archive the array as its root object, and everything will be handled cleanly within the "game" class. If you ever want to store other more complicated values, you can make additional classes and use the encodeObject and decodeObject functions.

You can look here for more info: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSCoding_Protocol/Reference/Reference.html

Upvotes: 1

Related Questions