Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to archive an NSArray of custom objects to file in Objective-C

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

like image 248
suse Avatar asked Dec 09 '22 14:12

suse


2 Answers

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.

like image 182
Joshua Avatar answered May 16 '23 06:05

Joshua


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

like image 21
Kalle Avatar answered May 16 '23 04:05

Kalle