Search code examples
objective-cxcodeplist

Read plist file during runtime


I have included a plist file in my program and called it locally

     NSString *plistpath = [[NSBundle mainBundle] pathForResource:@"pli" ofType:@"plist"];
     NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:plistpath];
     NSArray *cont = [dict allValues];

I want my program to read the file when I update it manually(not by program), add or delete data from the plist file, during runtime rather than having to stop my execution and start running it again. Is there ay way i can achieve this?

Please Help


Solution

  • Here is the way to save your data in .plist file

    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    
    // get documents path
    
      NSString *documentsPath = [paths objectAtIndex:0];
    
    // get the path to our Data/plist file
    
     NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"myData.plist"];
                                NSError *writeError = nil;
    
     NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:yourDictionary format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListImmutable error:&writeError];
    
            if(plistData)
              {
                 [plistData writeToFile:plistPath atomically:YES];
                  NSLog(@"Data saved sucessfully");
              }
              else
              {
                  NSLog(@"Error in saveData: %@", writeError.localizedDescription);
    
              }
    

    Read plist from the bundle and get Root Dictionary out of it

     NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
     NSString *documentsPath = [paths objectAtIndex:0];
     NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"myData.plist"];
    
    
     if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
        {
          plistPath = [[NSBundle mainBundle] pathForResource:@"myData" ofType:@"plist"];
        }
    
     NSDictionary *resultDic = [[NSDictionary alloc] initWithContentsOfFile:plistPath];