Adding items to NSMutableArray and saving/loading

2019-05-20 13:31发布

问题:

I've used this tutorial to create an app with a table view that is populated using an NSMutableArray. Now I'd like to add the functionality to add additional items to the array and save/load them. I've customized the Fruit class to look like this:

#import <UIKit/UIKit.h>

@interface Fruit : NSObject {
NSString *name;
NSString *instructions;
NSString *explination;
NSString *imagePath;
}

@property(nonatomic,copy) NSString *name;
@property(nonatomic,copy) NSString *instructions;
@property(nonatomic,copy) NSString *explination;
@property(nonatomic,copy) NSString *imagePath;

- (id)initWithName:(NSString*)n instructions:(NSString *)inst explination:(NSString *)why imagePath:(NSString *)img;

@end

and the Fruit.m file:

#import "Fruit.h"

@implementation Fruit
@synthesize name,instructions,explination,imagePath;

- (id)initWithName: (NSString*)n instructions:(NSString*)inst explination:(NSString *)why imagePath:(NSString *)img {
    self.name = n;
    self.instructions = inst;
    self.explination = why;
    self.imagePath = img;
    return self;
}
@end

and this works great, I can load two textviews and an imageView, instead of just one textview. But how would I go about saving any new items the user creates, and loading them (if they exist) when the app gets launched again?

回答1:

to save your array to disk you need a couple of things.

first you need to add some methods to your fruit class so it conforms to the NSCoding protocol.

The first method is - (id)initWithCoder:(NSCoder *)aDecoder. This method will be called when you create a Fruit object from a saved archive.
Second method is - (void)encodeWithCoder:(NSCoder *)aCoder. This method is used to save your fruit in an archive.

Sounds complicated? Actually it isn't. Just a couple lines of easy to understand code.

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.instructions = [aDecoder decodeObjectForKey:@"instructions"];
        self.explanation = [aDecoder decodeObjectForKey:@"explanation"];
        self.imagePath = [aDecoder decodeObjectForKey:@"imagePath"];
    }
    return self;
}

Look at first two lines of this init method. You have to call [super init] and do a check if self is not nil in your initWithName:instructions:explination:imagePath: method too. It won't change anything in this special case, but this will definitely change in the next few classes you write. So use it all the time.
I changed this for you. And I changed the spelling error.

- (id)initWithName: (NSString*)n instructions:(NSString*)inst explination:(NSString *)why imagePath:(NSString *)img {
    self = [super init];
    if (self) {
        self.name = n;
        self.instructions = inst;
        self.explanation = why;
        self.imagePath = img;
    }
    return self;
}

and the method for encoding:

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:name forKey:@"name"];
    [aCoder encodeObject:instructions forKey:@"instructions"];
    [aCoder encodeObject:explanation forKey:@"explanation"];
    [aCoder encodeObject:imagePath forKey:@"imagePath"];
}

It's not necessary that the key name matches the variable name. You don't need to do this. But in my opinion it adds some clarity. As long as you decode with the same name you've used for encoding you can use whatever you want.


First part is done. Next you need to load and save your NSMutableArray to a file. But to do this you need the path to the documents directory. So I created a little helper method that goes into your controller.

- (NSString *)applicationDocumentsPath {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

Then we need to load the array from disk.

NSString *path = [[self applicationDocumentsPath] stringByAppendingPathComponent:@"some.fruits"];

NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
if (!array) {
    // if it couldn't be loaded from disk create a new one
    array = [NSMutableArray array];
}

then you add as much fruits as you like, and finally, to save your array to disk you need this line.

BOOL result = [NSKeyedArchiver archiveRootObject:array toFile:path];

you can check result if the archive was done without error.


I guess this should get you started. Happy coding.



回答2:

You would need to persist your array on the disk and load it when the app launches.

See the answer to this question.



回答3:

Than you should read about archiving : NSArchiver

You would need to implement 2 method for your Fruit class :

EncodeWithEncoder and InitWithEncoder.

than you could archive you fruits array. Good Luck.