How to Save NSMutableArray into plist in iphone
Asked Answered
B

4

5

I am new in iphone, i want to save NSMutableArray data into plist file my Code is:

NSArray *array = [[NSArray alloc] initWithArray:self.artistDetailsArray];
[self.artistDetailsArray writeToFile:self.path atomically:YES];

but it shows 0 element in my plist path. please any help me.

Thanks in advance:

following is my code to store the data into plist and NSUserDefault. none of them is working for NSMutableArray/NSArray but working for NSString. IS there any max size limit to store in plist or UserDefault?? NSMutableArray contains only text/ set of NSDictionary.

please suggest me.

- (void)initialiseDataFromLocalStorage
{
       NSFileManager *fileManager = [NSFileManager defaultManager];
       NSError *error;
       NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
       NSString *documentsDirectory = [paths objectAtIndex:0];
       self.path = [documentsDirectory stringByAppendingPathComponent:@"saveLogin.plist"];
       if ([fileManager fileExistsAtPath:self.path] == NO) {
               NSString *pathToDefaultPlist = [[NSBundle mainBundle] pathForResource:@"saveLogin" ofType:@"plist"];
               if ([fileManager copyItemAtPath:pathToDefaultPlist toPath:self.path error:&error] == NO) {
                       NSAssert1(0,@"Failed with error '%@'.", [error localizedDescription]);
               }
       }

   // To get stored value from .plist
       NSDictionary *dict = [[NSDictionary alloc]initWithContentsOfFile:self.path];
       self.ResumedataDictionary = [[NSMutableDictionary alloc]initWithDictionary:dict];
       [dict release];
   self.artistDetailsArray = [[NSMutableArray alloc] initWithArray:[self.ResumedataDictionary objectForKey:@"artistDetailsDict"]];    
   // To get stored value from NSUserDefault
   NSUserDefaults *fetchData = [NSUserDefaults standardUserDefaults];
   self.artistDetailsArray = [fetchData objectForKey:@"artistDetailsDict"];    
}        

-(void)saveDataToLocalStorage
{    
   // To store value into .plist
   NSArray *array = [[NSArray alloc] initWithArray:self.artistDetailsArray];
   [ResumedataDictionary setObject:array forKey:@"artistDetailsDict"];
       [ResumedataDictionary writeToFile:self.path atomically:YES];  

   // To store value into NSUserDefault
   NSUserDefaults *fetchData = [NSUserDefaults standardUserDefaults];
   [fetchData setObject:self.artistDetailsArray forKey:@"artistDetailsDict"];    
}
Bergh answered 20/2, 2012 at 6:15 Comment(0)
M
5
NSMutableArray *array=[[NSMutableArray alloc] init];
    [array addObject:@"test"];
    [array writeToFile:@"/Users/parag/test.plist" atomically:YES];
    [array release];

or

NSMutableArray *array=[[NSMutableArray alloc] init];
[array addObject:@"test121"];
id plist = [NSPropertyListSerialization dataFromPropertyList:(id)array                            format:NSPropertyListXMLFormat_v1_0 errorDescription:@error];


 [plist writeToFile:@"/Users/parag/test.plist" atomically:YES];

Take a look at Creating Property Lists Programmatically

Museum answered 20/2, 2012 at 6:43 Comment(0)
I
4

look at this code which creates path to plist in documents directory:

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; //3

NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path]) //4
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:@”data” ofType:@”plist”]; //5

[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}

1) Create a list of paths.

2) Get a path to your documents directory from the list.

3) Create a full file path.

4) Check if file exists.

5) Get a path to your plist created before in bundle directory (by Xcode).

6) Copy this plist to your documents directory.

next read data:

NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

//load from savedStock example int value
int value;
value = [[savedStock objectForKey:@"value"] intValue];

[savedStock release];

write data:

NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

//here add elements to data file and write data to file
int value = 5;

[data setObject:[NSNumber numberWithInt:value] forKey:@”value”];

[data writeToFile: path atomically:YES];
[data release]
Isthmian answered 20/2, 2012 at 6:23 Comment(1)
Hi Neon, Thanks for prompt response. I used the same code and it's working for NSString value but not for NSMutableArray or NSArray. Any suggestion ??? :(Bergh
Q
3

You can use property lists (NSPropertyListSerialization or writeToFile: way). But be sure your array contains valid property list objects only (NSString, NSNumber, NSData, NSArray, or NSDictionary objects) and NSDictionary has only NSString keys. Custom (complex) objects have to be represented as dictionaries.

Or you should use approach with archives http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Archiving/Archiving.html through NSCoding protocol. Nice guide is here http://cocoadevcentral.com/articles/000084.php

Qadi answered 20/2, 2012 at 7:32 Comment(0)
C
0
NSData *serializedData;
        NSString *error;
        serializedData = [NSPropertyListSerialization dataFromPropertyList:YourArray(You can use dictionaries.strings..and others too)
        format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
        if (serializedData) {
        // Serialization was successful, write the data to the file system // Get an array of paths.

       NSArray *documentDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDir = [NSString stringWithFormat:@”%@/serialized.xml”,
         [documentDirectoryPath objectAtIndex:0]];
        [serializedData writeToFile:docDir atomically:YES];
 }
        else {
        // An error has occurred, log it
        NSLog(@”Error: %@”,error); }
        }
Cavefish answered 20/2, 2012 at 6:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.