views:

133

answers:

2

Hello,

Can you show me the syntax or any sample programs to archive an NSArray of custom objects in Objective-C?

A: 

Check out NSUserDefaults.

For Archiving your array, you can use the following code:

[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:myArray] forKey:@"mySavedArray"];

And then for loading the custom objects in the array you can use this code:

NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *savedArray = [currentDefaults objectForKey:@"mySavedArray"];
if (savedArray != nil)
{
        NSArray *oldArray = [NSKeyedUnarchiver unarchiveObjectWithData:savedArray];
        if (oldArray != nil) {
                customObjectArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
        } else {
                customObjectArray = [[NSMutableArray alloc] init];
        }
}

Make sure you check that the data returned from the user defaults is not nil, because that may crash your app.

The other thing you will need to do is to make your custom object to comply to the NSCoder protocol. You could do this using the -(void)encodeWithCoder:(NSCoder *)coder and -(id)initWithCoder:(NSCoder *)coder methods.

Joshua
A: 

If you want to save to a file (rather than using NSUserDefaults) you can use -initWithContentsOfFile: to load, and -writeToFile:atomically: to save, using NSArrays.

Example:

- (NSArray *)loadMyArray
{
    NSArray *arr = [NSArray arrayWithContentsOfFile:
        [NSString stringWithFormat:@"%@/myArrayFile", NSHomeDirectory()]];
    return arr;
}

// returns success flag
- (BOOL)saveMyArray:(NSArray *)myArray
{
    BOOL success = [myArray writeToFile:
        [NSString stringWithFormat:@"%@/myArrayFile", NSHomeDirectory()]];
    return success;
}

There's a lot of examples on various ways to do this here: http://www.cocoacast.com/?q=node/167

Kalle