How to Read Data Structure from .Plist File into Nsarray

How to read data structure from .plist file into NSArray


NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"league" ofType:@"plist"];
contentDict = [NSDictionary dictionaryWithContentsOfFile:plistPath];

That answer is correct - are you sure that your file is in the app? Did you add it to your project, and check to see if it gets copied into your app bundle? If not, it might be the file was not added to the target you are building, an easy mistake to make especially if you have multiple targets.

reading objects from plist to NSArray

If you're storing and retrieving a list of patients, then over time as your app matures you will likely need to access them in various ways. CoreData and/or Sqlite offer more robust storage mechanisms that offer rich querying, indexing and CRUD operations.

CoreData will offer a designer to design your logical objects and take care of the persistance to sqlite for you. If you want more control, you can work with sqlite and if you do, fmdb is a good wrapper class.

Unless you're doing this as a learning sample to learn plists, I wouldn't recommend tracking patients in a plist. If that's the case, then here's another SO article on persisting arrays to plists:

How to read data structure from .plist file into NSArray

From that post:

NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"league" ofType:@"plist"];
contentArray = [NSArray arrayWithContentsOfFile:plistPath];

Hope that helps

How to read Array from plist iOS

First of all Check your plist looks like:

Sample Image

Now write following lines where you are accessing your plist

Objective-C:

NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Values" ofType:@"plist"]];
NSArray *array = [dictionary objectForKey:@"keyarray1"];
NSLog(@"dictionary = %@ \narray = %@", dictionary, array);

Here is the complete screen shot (with log output) of my work window:

Sample Image

Swift:

let dictionary = NSDictionary(contentsOfFile: Bundle.main.pathForResource("Values", ofType: "plist")!);
let array = dictionary?["arrayKey"] as! NSArray
print("dictionary=", dictionary, "\narray =", array)

Sample Image

Swift - read plist file to an array?

Change your root object to Array, then

var myEnglishArray: [String] = []
if let URL = NSBundle.mainBundle().URLForResource("englishArray", withExtension: "plist") {
if let englishFromPlist = NSArray(contentsOfURL: URL) as? [String] {
myEnglishArray = englishFromPlist
}
}

Create NSArray from Array within Plist

When you read in the dictionary, the arrays it contains are created for you. You merely need to access them by asking for the -objectForKey: using the appropriate key.

NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:filePath];
NSArray *georgeWashingtonInfo = [dictionary objectForKey:@"1"];
NSArray *johnAdamsInfo = [dictionary objectForKey:@"2"];
NSArray *thomasJeffersonInfo = [dictionary objectForKey:@"3"];

How do I read a value of a property list file key into a string for iphone app using Xcode

Load the .plist into a NSDictionary like:

NSString *path = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];

Loop through the NSDictionary using something like:

for (id key in dictionary) {
NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

Read/write data from a plist of dictionaries and arrays, and load different levels into a TableView

Let's say that you have a plist file like this:

plist file image

and this code:

@implementation ViewController


NSDictionary *dictionary;

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

NSMutableArray *array=[[NSMutableArray alloc]init];
array=[NSMutableArray arrayWithContentsOfFile:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"root.plist"]];

dictionary = [array objectAtIndex:0];


}

- (NSString *)applicationDocumentsDirectory {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSLog(@"numberOfSectionsInTableView:%lu",(unsigned long)dictionary.count);
return dictionary.count;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [[[dictionary allKeys] objectAtIndex:section] capitalizedString];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
NSArray *peopleArray = [dictionary objectForKey:[[dictionary allKeys] objectAtIndex:indexPath.section]];

cell.textLabel.text = [[peopleArray objectAtIndex:indexPath.row]objectForKey:@"name"];
cell.detailTextLabel.text = [NSString stringWithFormat:@"Color:%@ - Gender:%@",[[peopleArray objectAtIndex:indexPath.row]objectForKey:@"favorite color"],[[peopleArray objectAtIndex:indexPath.row]objectForKey:@"gender"]];

return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSString *key =[[dictionary allKeys] objectAtIndex:section];
NSLog(@"numberOfRowsInSection:%lu",(unsigned long)[[dictionary objectForKey:key] count]);
return [[dictionary objectForKey:key] count];
}

it will give you this output:

(Supposed you have a tableView set up with Delegate and DataSource)

Output iPhone Simulator image

I know that you asked for having the "Friends" and "Enemies" in different TableViews, but I use both in the same tableView but in different sections. But my code can get you started.

If you need extra help about the UITableView, see Apple UITableView Class Reference

If this is necessary, I used this code to generate the example plist-file in my test-project:

NSMutableArray *root=[[NSMutableArray alloc]init];
NSMutableArray *friendsarray = [[NSMutableArray alloc]init];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setObject:@"Jill" forKey:@"name"];
[dict setObject:@"green" forKey:@"favorite color"];
[dict setObject:@"female" forKey:@"gender"];

[friendsarray addObject:dict];

NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
[dict2 setObject:@"Bob" forKey:@"name"];
[dict2 setObject:@"Blue" forKey:@"favorite color"];
[dict2 setObject:@"male" forKey:@"gender"];

[friendsarray addObject:dict2];

NSMutableArray *enemiesarray = [[NSMutableArray alloc]init];


NSMutableDictionary *dict3 = [[NSMutableDictionary alloc]init];
[dict3 setObject:@"Michael" forKey:@"name"];
[dict3 setObject:@"Red" forKey:@"favorite color"];
[dict3 setObject:@"male" forKey:@"gender"];

[enemiesarray addObject:dict3];

NSMutableDictionary *d = [[NSMutableDictionary alloc]init];
[d setObject:friendsarray forKey:@"friends"];
[d setObject:enemiesarray forKey:@"enemies"];


[root addObject:d];

[root writeToFile:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"root.plist"] atomically:YES];

how to read data from a plist saved in document directory and display that as pdf in a new view?

Updated Solution
Replace the method in pdfgenerate

- (IBAction)pdfPressed:(id)sender {

NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,NSUserDomainMask, YES);
NSString *documentsDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Data.plist"];

NSLog(@"File Path: %@", filePath);

NSArray *students = [NSArray arrayWithContentsOfFile:filePath];

// get a temprorary filename for this PDF
filePath = NSTemporaryDirectory();
self.pdfFilePath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%f.pdf", [[NSDate date] timeIntervalSince1970] ]];

// Create the PDF context using the default page size of 612 x 792.
// This default is spelled out in the iOS documentation for UIGraphicsBeginPDFContextToFile
UIGraphicsBeginPDFContextToFile(self.pdfFilePath, CGRectZero, nil);

// get the context reference so we can render to it.
CGContextRef context = UIGraphicsGetCurrentContext();

int currentPage = 0;

// maximum height and width of the content on the page, byt taking margins into account.
CGFloat maxWidth = kDefaultPageWidth - kMargin * 2;
CGFloat maxHeight = kDefaultPageHeight - kMargin * 2;

// we're going to cap the name of the class to using half of the horizontal page, which is why we're dividing by 2
CGFloat classNameMaxWidth = maxWidth / 2;

// the max width of the grade is also half, minus the margin
CGFloat gradeMaxWidth = (maxWidth / 2) - kColumnMargin;
CGFloat grade1MaxWidth = (maxWidth / 2) - kColumnMargin;
CGFloat grade2MaxWidth = (maxWidth / 2) - kColumnMargin;


// only create the fonts once since it is a somewhat expensive operation
UIFont* studentNameFont = [UIFont boldSystemFontOfSize:17];
UIFont* classFont = [UIFont systemFontOfSize:15];

CGFloat currentPageY = 0;
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, kDefaultPageWidth, kDefaultPageHeight), nil);
currentPageY = kMargin;
// iterate through out students, adding to the pdf each time.
for (NSDictionary* student in students)
{
// every student gets their own page
// Mark the beginning of a new page.


// draw the student's name at the top of the page.
NSString* name = [NSString stringWithFormat:@"%@",
[student valueForKey:@"city"]];

CGSize HeaderSize = [name sizeWithFont:studentNameFont forWidth:maxWidth lineBreakMode:NSLineBreakByWordWrapping];


// iterate through the list of classes and add these to the PDF.
//NSArray* classes = [student objectForKey:@"Classes"];

NSString* className = [student valueForKey:@"state"];
NSString* grade = [student valueForKey:@"cityPrice"];
NSString* grade1 = [student valueForKey:@"cityText"];
NSString* grade2 = [student valueForKey:@"cityQuantity"];

// before we render any text to the PDF, we need to measure it, so we'll know where to render the
// next line.
CGSize DetailSize = [className sizeWithFont:classFont constrainedToSize:CGSizeMake(classNameMaxWidth, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];

// if the current text would render beyond the bounds of the page,
// start a new page and render it there instead

if (HeaderSize.height + DetailSize.height+currentPageY > maxHeight) {
// create a new page and reset the current page's Y value
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, kDefaultPageWidth, kDefaultPageHeight), nil);
currentPageY = kMargin;
currentPage++;
}
[name drawAtPoint:CGPointMake(kMargin, currentPageY) forWidth:maxWidth withFont:studentNameFont lineBreakMode:NSLineBreakByWordWrapping];


// draw a one pixel line under the student's name
CGContextSetStrokeColorWithColor(context, [[UIColor blueColor] CGColor]);
CGContextMoveToPoint(context, kMargin, currentPageY+HeaderSize.height);
CGContextAddLineToPoint(context, kDefaultPageWidth - kMargin, currentPageY+HeaderSize.height);
CGContextStrokePath(context);

// render the text
[className drawInRect:CGRectMake(kMargin, currentPageY+HeaderSize.height, classNameMaxWidth, maxHeight) withFont:classFont lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft];

// print the grade to the center of the class name
[grade drawInRect:CGRectMake (kMargin , currentPageY+HeaderSize.height, gradeMaxWidth, maxHeight) withFont:classFont lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentCenter];
// print the grade1 to the right of the class name
[grade1 drawInRect:CGRectMake(kMargin , currentPageY+HeaderSize.height, grade1MaxWidth, maxHeight) withFont:classFont lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentRight];

[grade2 drawInRect:CGRectMake(kMargin , currentPageY+HeaderSize.height, grade2MaxWidth, maxHeight) withFont:classFont lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentRight];
// increment the page number.
currentPageY = currentPageY+DetailSize.height+HeaderSize.height+30;

}

// end and save the PDF.
UIGraphicsEndPDFContext();

// Ask the user if they'd like to see the file or email it.
UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"Would you like to preview or email this PDF?"
delegate:self
cancelButtonTitle:@"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:@"Preview", @"Email", nil];
[actionSheet showInView:self.view];





}

OLD Solution

   NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,NSUserDomainMask, YES);
NSString *documentsDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Data1.plist"];

NSLog(@"File Path: %@", filePath);

NSArray *students = [NSArray arrayWithContentsOfFile:filePath];

You have to get the value for specific key not an object for that key

[student objectForKey:@"city"];

Instead of the above line use it like this

[student valueForKey:@"city"];

You storing the data as Array so you can get the array of content, The above code will help you to fetch the array of object in student variable as you did in pdfpressed, the you can proceed the same to draw the content in pdf file.

Sample Image



Related Topics



Leave a reply



Submit