-2

I am trying to get particular data from plist file without creating new object.

NSArray *fruits = @[@"Apple", @"Mango", @"Pineapple", @"Plum", @"Apricot"];

NSString *filePathFruits = [documents stringByAppendingPathComponent:@"fruits.plist"];
[fruits writeToFile:filePathFruits atomically:YES];

NSDictionary *miscDictionary = @{@"anArray" : fruits, @"aNumber" : @12345, @"aBoolean" : @YES};

NSString *filePathDictionary = [documents stringByAppendingPathComponent:@"misc-dictionary.plist"];
[miscDictionary writeToFile:filePathDictionary atomically:YES];

NSArray *loadedFruits = [NSArray arrayWithContentsOfFile:filePathFruits];
NSLog(@"Fruits Array > %@", loadedFruits);

NSString *string1 = [[NSArray arrayWithContentsOfFile:filePathDictionary] objectAtIndex:1];
NSString *string2 = [loadedFruits objectAtIndex:1];

NSLog(@"Without New array object: %@",string1);  // output is : null
NSLog(@"With array object : %@",string2);  // output is : mango

Can you explain difference between string1 and string2 creation?

Andre
  • 26,751
  • 7
  • 36
  • 80
Rajesh
  • 124
  • 9
  • Possible duplicate of [How do I read a value of a property list file key into a string for iphone app using Xcode](http://stackoverflow.com/questions/12250739/how-do-i-read-a-value-of-a-property-list-file-key-into-a-string-for-iphone-app-u) – Bug Oct 27 '15 at 12:03

2 Answers2

0

Very Easy See This Answer

@interface ViewController ()

@property (nonatomic, strong) NSDictionary* pDictionary;

@end

@implementation ViewController

// other code here

// within readDefinitionsFile method
self.pDictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];

Use pDictionary to retrieve the definition you are interested in.

NSString* plistData = [self.pDictionary objectForKey:@"aKeyYouWillRetrieveFromSomewhere"];
if(definition) {
    NSLog(@"definition is %@ for key %@", plistData, @"aKeyYouWillRetrieveFromSomewhere");
} else {
    NSLog(@"no data for key %@", @"aKeyYouWillRetrieveFromSomewhere");
}
Community
  • 1
  • 1
Bug
  • 2,576
  • 2
  • 21
  • 36
0

If your plist file contains an array, like your fruits array, you can use +[NSArray arrayWithContentsOfFile:]. But if it contains a dictionary (which is the case here), you have to use +[NSDictionary dictionaryWithContentsOfFile:].

If you don't know in advance the data type, check out the NSPropertyListSerialization class which will work with both.

deadbeef
  • 5,409
  • 2
  • 17
  • 47