开发者

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

开发者 https://www.devze.com 2023-01-11 22:51 出处:网络
Can you sh开发者_Python百科ow me the syntax or any sample programs to archive an NSArray of custom objects in Objective-C?Check out NSUserDefaults.

Can you sh开发者_Python百科ow me the syntax or any sample programs to archive an NSArray of custom objects in Objective-C?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消