I have a NSMutableArray, each item in this array is different class. In each class has many field such as CPPlot, identifier,... (I am using CorePlot to develop a stock application). Now I would like to store this NSMutableArray to load when user reopen application, this will load all the chart they used before.
I try to figure out how to do that in Stackoverflow. And I found out there were 2 solutions:
NSUserDefaults
SQLite database
In NSUserDefaults, when I want to store NSMutableArray, I must implement with NSKeyedArchiver to archive and unarchive array object, also do NSCoding protocol for each item in array object. But I can not do this solution because in each item, it has some fields from CorePlot library, so that I can not use NSCoding to these fields.
SQLite database, I can not use this solution because each item in array object is different class.
I would like to ask if any other solution to solve this problem?
I hope my words are clear enough to understand.
Thanks
I would suggest you figure out what kind of data is at the root of your CorePlot objects. If it is integers, then simply store them in NSUserDefaults, and then simply rebuild your NSMutableArray on re-opening the app. Another option is to store your items in a separate plist file.
Use this method to save:
- (NSArray *)applicationDataFromFile:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirecotiresInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory
stringByAppendingPathComponent:fileName];
NSArray *myData = [NSArray arrayWithContentsOfFile:appFile];
return myData;
}
- (BOOL)saveToFileForStringArray:(NSMutableArray *)array
toFile:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
NSLog(#"Documents directory not found!");
return NO;
}
NSString *appFile = [documentsDirectory
stringByAppendingPathComponent:fileName];
return ([array writeToFile:appFile atomically:YES]);
}
Related
i am doing one iphone app, for that i have to store bulk of MP3 song and images.
can ay one tell me what is the best to store those in terms of performance.
Store the image and songs in the application directory. This is best and easy way to handle. Try the following code. it will be help you.
//Store Image/Songs files to Application Directory
+(BOOL)writeToFile:(NSData *)data fileName:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
return [data writeToFile:appFile atomically:YES];
}
//Image/songs - Retrieve from Application Directory
+(NSData *)readFromFile:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
if (myData) {
return myData;
}
return nil;
}
store the MP3 song and images into resources folder of your app project and give the refrences in the sqlite database(because saving large files in sqlite database is not a good practice)
I would suggest you to store all items of large size on the device disk, i.e, Documents directory and store their physical path in core data or sqlite or at least in a plist file so that you can retrieve them as per your convenience.
I have an app that is supposed to save to a file and later on load it. Now, I have not had ANY problems what so ever on ios 4, so this is perplexing. This has happened on all my apps saving and loading.
Heres the code:
- (NSString *)pathOfFile{
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsFolder = [paths objectAtIndex:0];
return [documentsFolder stringByAppendingFormat:#"awesome.plist"];
}
Later in in the app...
[array writeToFile:[self pathOfFile] atomically:YES];
And then when I attempt to load it...
if ([[NSFileManager defaultManager] fileExistsAtPath:[self pathOfFile]]) {
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filepath];
achi.text = [array objectAtIndex:0];
}
My app actually just skips over the if statement (Meaning that it can't find the file I think).
Please help, and if you have different methods of saving files, I would be glad to hear to hear them.
Your - (NSString *)pathOfFile method is wrong. It should be:
- (NSString *)pathOfFile
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsFolder = [paths objectAtIndex:0];
return [documentsFolder stringByAppendingPathComponent:#"awesome.plist"];
}
In your -(NSString *)pathOfFile method, don't use stringByAppendingFormat:. When working with file paths, you should instead use stringByAppendingPathComponent:, as it will ensure that the appropriate slash characters are added (or removed, if there are too many):
return [documentsFolder stringByAppendingPathComponent:#"awesome.plist"];
The comment to my question was what solved the problem, but as I can't give him the correct answer, I'll just write paste his answer here:
Did you make sure the directory is there? Sometimes that Documents directory must be created.
I have interesting thing here, I'm using xcode 4 for my project and I want to create simple .plist file to save several values which will be used for different purposes during code execution. This is the code I use to create plist:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"somelist.plist];
}
last line of code which should append plist name to path do not do its job. Plist is never created. Now, strange thing, i manage to create one few days ago using same code. After that, I only move this piece of code in AppDelegate because, I call this code from different places. I discovered that isn't working when I switch to 4.3 emulator and then also try it on iphone device. When I switch to 4.2 emulator it works because there is already a plist, however when I change its name (to create new one) nothing happens - meaning, list is not created. I also try moving code back to original place, but that didn't gave desired result.
Your code should not create a plist anyway, only return a path. In order to actually save a plist at the chosen path, you could choose several approaches, for example use the following method on NSDictionary:
- (void)saveDictionary
{
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:#"bla" forKey:#"test"];
NSString *path = [self datafilePath];
[dictionary writeToFile:path atomically:YES];
}
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"somelist.plist];
}
I was trying to use a plist to store an array with the below code:
NSString *name = firstName.text;
NSString *path = [[NSBundle mainBundle] pathForResource:#"Names" ofType:#"plist"];
NSMutableArray *namesArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
[namesArray addObject:name];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[paths release];
NSString *docDirPath = [documentsDirectory stringByAppendingPathComponent:#"Names.plist"];
[namesArray writeToFile:docDirPath atomically:YES];
namesArray = [[NSMutableArray alloc] initWithContentsOfFile:docDirPath];
This code seems to work. Using NSLog, I have found that after this code executes the plist contains what I want it to, however, my program crashes because it generates an EXC_BAD_ACCESS on a device, and on the simulator it just crashes without an explanation. Does anyone know why that might happen?
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES); //Auto-released array
NSString *documentsDirectory = [paths objectAtIndex:0];
[paths release]; //Oh noes!
You don't own the reference to paths, so don't release it. Remove [paths release] and I'll bet you're fine. You're crashing because the autorelease pool is releasing paths after you've already done it yourself.
Quoth the guide:
You only release or autorelease objects you own. You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” ... or if you send it a retain message.
Have you checked, at which place it is giving EXC_BAD_ACCESS error.
In your code there are two wrong things; those are.
The Plist file consists a dictionary not an array, Here in the code you are copying the file data to an array. and saving the array to the plist file.
Second one is you are releasing the "paths" array, with out completion of usage of it. you have to release that array at the end of the statements; like after updating the array to the file.
Regards,
Satya
I have one dictionary I need to save into a plist. The paletteDictionary always returns nil:
- (void)saveUserPalette:(id) sender
{
[paletteDictionary setObject:matchedPaletteColor1Array forKey:#"1"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"UserPaletteData.plist"];
// write plist to disk
[paletteDictionary writeToFile:path atomically:YES];
}
I'm reading the data back in a different view like:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"UserPaletteData.plist"];
NSMutableDictionary *plistDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:path];
if(plistDictionary==nil ){
NSLog(#"failed to retrieve dictionary from disk");
}
Can you mention what object is "matchedPaletteColor1Array". I believe, its some custom class object. With my knowledge the writable objects must conform to NSCoding, which NSString,NSDate etc are already, So in given code, setting "matchedPaletteColor1Array" as some string will work.
You can look at following post to make your object NSCoding enabled. objects conforming to nscoding will not writetofile
Run your application in the simulator and browse to the following path:
~/Library/Application Support/iPhone Simulator/User/Applications/{A GUID}/Documents
Where A GUID will be a string like this: 06430A38-AFAC-4C68-8F39-DBD6C81A5AA6 (it's probably the Last Modified folder).
Verify that UserPaletteData.plist is present and load it up in Property List Editor.app to verify that it contains some data.
Also make sure that the you use only the following data types in your dictionary otherwise it will fail to write to a plist: (NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary).
To verify that the dictionary you are attempting to save to disk is valid for a plist, try the following:
for (id key in paletteDictionary)
{
NSLog(#"key: %#, value: %#, class: %#", key, [paletteDictionary objectForKey:key], NSStringFromClass([[paletteDictionary objectForKey:key] class]));
}
That should tell you if any of your objects are the wrong data type for a plist.
If that is still not helping, then you should make sure that paletteDictionary has been alloc/init'ed before saveUserPalette is called.
Check that you are allocating (alloc/init) paletteDictionary before you use it.