views:

63

answers:

2

I currently write to and read from an array of data, and use the index of each element to achieve something. I need a way to store this array, I looked at the user defaults, but that stores a dictionary, with retieval using keys. I will not know what key was stored.

What is the best was to store ths array of data on the iphone?

Regards

+2  A: 

NSKeyedArchiver, a concrete subclass of NSCoder, provides a way to encode objects (and scalar values) into an architecture-independent format that can be stored in a file.

So you can serialize anything you like to a file:

// need a path
- (NSString*) getPath
{ 
    NSString* path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    return [path stringByAppendingPathComponent:@"someInfo"];
}

// save an array
- (void) save:(NSArray*)array
{
    [NSKeyedArchiver archiveRootObject:array toFile:[self getPath]];    
}

// get that array back
- (NSArray*) load
{
     return [NSKeyedUnarchiver unarchiveObjectWithFile:[self getPath]];       
}

You might want to serialize a dictionary of arrays if you have more than one you want to store.

Cannonade
Appreciate it. :D
alJaree
What does the "someInfo" relate to?
alJaree
That's the name of the file.
Johan Kool
where is the file created? In that call?
alJaree
+1  A: 

It is possible to store an array in NSUserDefaults. It does however depend on the kind of objects the array holds. NSKeyedArchiver is another good option, as is storing the array as a plist. It could even be that CoreData is the best choice for you. It all depends on the expected size of your data and how you use it. NSKeyedArchiver seems a fair enough middle ground for many situations, but to answer you question more info is needed.

Johan Kool
I am just storing NSStrings in the array. I take user input from a textfield(the user saves a title for a 'favorite' which I add the picture index which they wanted to save)Then when reading from the array, I just cut the index off, populate a tableview with all the titles in the array. A user can then select a favorite and the image reference is fetched from the array and loaded on screen. It shouldnt be more than 50 strings.
alJaree
Sounds like storing to a plist would be most appropriate in your case. I do suggest switching to using a NSDictionary though instead of appending the picture index. A custom class for your favorite may be even better, but than you should use NSKeyedArchiver.
Johan Kool
I tried the NSDictionary, but the problem is I use the index of the array to access values I dont know the key of. All I want to do know is store the array, then load it. Right now I read and write the array, so I just want to serialize and deserialize it.
alJaree
I am suggesting an array of dictionaries. You can access the values in the dictionaries by keys you define, for example "title" and "index".
Johan Kool
That will work nicely, thanks.
alJaree