4

I have an NSMutableArray with many objects in it. Some are NSStrings, others are NSMutableArrays, others are NSNumbers. What is the best way to store this data so that the app could use it again?

The array needs to stay in order as well.

I'm thinking a plist or NSUserDefaults?

Many thanks

2 Answers 2

3

Consider using NSKeyedArchiver.

// Archive
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:theArray];
NSString *path = @"/Users/Anne/Desktop/archive.dat";
[data writeToFile:path options:NSDataWritingAtomic error:nil];

// Unarchive
NSString *path = @"/Users/Anne/Desktop/archive.dat";
NSMutableArray *theArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

It works great, especially in case the array contains more then strings and numbers.
This way you can be sure the unarchived array is identical to the original.

Sign up to request clarification or add additional context in comments.

Comments

2

Assuming the other arrays also contain only numbers, strings, and arrays (or other property list types), a plist would be a great way to store your data. It will keep it's order, and is simple to use.

To write an array to a plist file, use writeToFile:atomically:.

[myArray writeToFile:@"path/to/file.plist" atomically:YES];

To read it, use initWithContentsOfFile:.

myArray = [[NSMutableArray alloc] initWithContentsOfFile:@"path/to/file.plist"];

However, that will create a mutable array with non-mutable contents. To create an array with mutable contents, you can use CFPropertyListCreateDeepCopy.

NSArray *temp = [[NSArray alloc] initWithContentsOfFile:@"path/to/file.plist"];
myArray = (NSMutableArray*) CFPropertyListCreateDeepCopy(kCFAllocatorDefault,(CFArrayRef)temp,kCFPropertyListMutableContainers);
[temp release];

1 Comment

The "only contains numbers strings and arrays" (and dates and dictionaries and NSData and NSNull) part, along with the "creates an immutable array" part are only true if you're using NSUserDefaults or writing out to a PLIST. PLIST (and user defaults, same format) only allows those types BUT if your class can be archived/unarchived, it can be stored as an NSData instance inside a PLIST/user defaults just fine. If you're going with keyed archiving, as Anne suggested above, you might as well store this information in its own file. User defaults /plist will work for the case you described, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.