Search code examples
iphoneobjective-cnsarraysaving-data

How to save an array full of custom classes in iOS?


In an iOS application I am creating for a school project, I am having trouble saving data that is stored in an NSMutableArray. The array is created in the app delegate file, and then delegates for it are created in various other view controller files. The data stored in the array consists of custom classes made up of NSStrings and NSNumbers as properties.

I've read and followed many examples on this site for about a week now, but I can't for the life of me figure it out. I've also looked into core data, but I couldn't figure out how to implement that without completely starting over, and I'm pressed for time unfortunately.

Things I have tried:

Archiving in the WillTerminate method. (activityArray is my array)

- (void)applicationWillTerminate:(UIApplication *)application {
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* arrayFile = [documentsPath stringByAppendingPathComponent:@"arrayFile"];
[NSKeyedArchiver archiveRootObject:activityArray toFile:arrayFile];
[activityArray release];

And then unarchiving in the didFinishLaunchingWithOptions method of the AppDelegate file

    NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *arrayFile = [documentsPath stringByAppendingPathComponent:@"arrayFile"];
if ([fileManager fileExistsAtPath:arrayFile]) {
    NSLog(@"yes");
    activityArray = [NSMutableArray arrayWithContentsOfFile:arrayFile];
} else {
    activityArray = [[NSMutableArray alloc] init];
}

As per suggestions on other questions, I did the following in the custom classes I have (this class has 2 NSStrings, activityName and activityDescription).

- initWithCoder:(NSCoder *)aCoder {
self = [super init];
activityName = [[aCoder decodeObjectForKey:@"activityName"] retain];
activityDescription = [[aCoder decodeObjectForKey:@"activityDescription"] retain];
return self;
 }

-(void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:activityName forKey:@"activityName"];
[aCoder encodeObject:activityDescription forKey:@"activityDescription"];
}

But none of this seems to work for me. Any help is gratefully appreciated. I feel like this should be a rather easy thing, but I just can't seem to get it.


Solution

  • Core Data is actually very simple and fast to implement. I made a blog post on quickly getting it setup a few months ago. Simply make entities to represent the different classes you have created or add the @dynamic properties yourself.

    Keep in mind that Core Data behaves the same as an Array in that only objects can be stored. Thus you need to use NSNumber for int\floats, etc.