I have this tableview in my app which has a particular item name such as "Apple". When the user taps on that selected item they are directed to a detailView that views an image and description of that selected item. I was thinking to use plist´s to do this, but I don't know how to. Please help me.
I looked at some sources such as iCodeBlog but they don´t really explain retrieving and saving so well. Maybe you people can also give reference to some links that describe this better.
Heres a plist that I have tried. Each of the items (Orange, Apple) have the data that I want to display in my detailView. I basically want to display the data shown.
Here is an example view controller which will do what you want. I named the class DetailViewController and loaded the plist from Details.plist in the app's resources. Images are also located in the app's resources.
DetailViewController.h
#import <UIKit/UIKit.h>
#interface DetailViewController : UIViewController {
UILabel *description;
UIImageView *imageView;
NSString *selectedItem;
}
#property (nonatomic, retain) IBOutlet UILabel *description;
#property (nonatomic, retain) IBOutlet UIImageView *imageView;
#property (nonatomic, copy) NSString *selectedItem;
#end
DetailViewController.m
#import "DetailViewController.h"
#implementation DetailViewController
#synthesize description, imageView, selectedItem;
- (void)viewDidLoad {
NSDictionary *details = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Details" ofType:#"plist"]];
details = [details objectForKey:self.selectedItem];
self.description.text = [details objectForKey:#"description"];
self.imageView.image = [UIImage imageNamed:[details objectForKey:#"image"]];
}
#end
Then, all you have to do is update the selectedItem property before loading the view and create a NIB file with the description label and image view attached to their outlets.
Plists are really useful for many cases:
+ (NSMutableDictionary*) containerDictionary {
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"ContainerGraphics.plist"];
NSMutableDictionary *plistData = [NSMutableDictionary dictionaryWithContentsOfFile:finalPath];
return plistData;
}
This loads a plist file (Property List) called "ContainerGraphics.plist" from my apps bundle.
The plist file is actually just an XML file. You can build one in Xcode by selecting "new file" -> "resource" -> "Property list".
You don't really say what it is you don't understand, so if there is something specific that you find hard to comprehend, please elaborate:)
EDIT:
With the plist you post, use my above approach to "load in" the plist file.
Then it is an NSDictionary of NSDictionaries..
So to get to the "Apple" dictionary you go:
NSDictionary *appleDictionary = [plistData objectForKey:#"Apple"];
Which means something along - go into the list and retrieve the "Apple" dictionary.
Now to get the image and description values you would go:
NSString *imagePath = [appleDictionary objectForKey:#"image"];
NSString *descriptionString = [appleDictionary objectForKey:#"description"];
That is pretty much what there is to it.
If you have a a tableView that need to be populated with this data there is a catch!
The data inside an NSDictionary has no order. So you can't just reference [dictionary objectAtIndex:indexPath.row] as you would do with an array of data for a tableView.
What you do then is to first get the plistData, as in my first example.
(do this in viewDidLoad).
Then you extract all the keys from the plistData dictionary - notice that the "top dictionary is specific, "Apple, "Orange" etc. not values you want to hardcode into your app. But, the dictionaries inside these dictionaries are general, image, description…
So:
NSArray *allKeys = [plistData allKeys];
the allKey array now contains keys (Apple, Orange, etc.)to get to the NSDictionaries in the plistData.
In the cellForRowAtIndexPath method you can now go:
NSDictionary *dictionaryForCurrentCell = [plistData objectForKey:[allKeys objectAtIndex:indexPath.row]];
[cell.textLabel setText:[dictionaryForCurrentCell objectForKey:#"image"]];
[cell.detailLabel setText:[dictionaryForCurrentCell objectForKey:#"description"]];
Hope it helps:)
Pass an NSString to the detail view and load the item based on the NSString, This could be a particular dictionary name, or item in an array.
newDetailViewController.currentItem = #"Array1";
and in my detail view, define:
.h
NSString *currentItem;
#property(nonatomic,retain) NSString *currentItem;
.m
#synthesize currentItem;
Now currentItem in your detailView controller will be "Array1", since that is what we passed to it.
It all depends on really how your plist is setup, are you using an NSArray, an NSDictionary?
There are plenty of ways you can put this to use:
NSString *current = [NSString stringWithFormat:#"%#/%#",appDocsPath,currentItem];
NSMutableDictionary* dict = [[[NSMutableDictionary alloc] initWithContentsOfFile:current] autorelease];
EDIT FROM QUESTION:
Using the example above:
aLabel.text = [dict objectForKey#"description"];
Create an array in a plist with a number of items which is equal to the number of rows. Create a string called description and a string called image in each item. Get the number of the selected row in didSelectRowAtIndex: method. Store the dictionary in an NSDictionary
[myDictionary initWithDictionary:[myArray objectAtIndex:indexPath.row]]
Then get the imagestring and the description string by calling
[myDictionary objectForKey:#"image"]
and pass these strings to the detail view.
Related
I am trying to store all of the items scrolled past in my UITableView in an NSMutableArray. In my cellForRowAtIndexPath method I include the code below. All of the objects (Id, currentTime, et...) are NSStrings.
I am trying to compile all of them into a single array, but I don't think I am doing this correctly. I think I might be overwriting the dictionary in every single cellForRowAtIndexPath.
Any help would be great. At the end, I just want a single array that allows me to look up various aspects of the "rows/cells" that were scrolled past...
In my .m file:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:Id forKey:#"key1"];
[dict setObject:currentTime forKey:#"key2"];
[dict setObject:textForMyLabel forKey:#"key3"];
[dict setObject:placeLatitude forKey:#"key4"];
[dict setObject:placeLongitude forKey:#"key5"];
[scrolledPast addObject:dict];
NSLog(#"array: %#", dict);
In my .h file:
#interface viewController {
NSMutableArray *scrolledPast;
}
#property (nonatomic, retain) NSMutableArray *scrolledPast;
You need to initialize your scrolledPast.
Do this in your viewDidLoad:
- (void) viewDidLoad {
// .....
scrolledPast = [NSMutableArray array];
}
Having a little issue with NSDictionary and sorting. I've read a few posts on here about using certain methods such as sortedArrayUsingSelector and keysSortedByValueUsingComparator but cannot quite grasp it. At the moment I have a Table View Controller displaying some data correctly. The only issue I have is the order it is displaying it (or rather, the order of the sections).
In the declaration file:
#interface SettingsTableViewController : UITableViewController {
NSDictionary *tableContents;
NSArray *keys;
}
#property (nonatomic,retain) NSDictionary *data;
#property (nonatomic,retain) NSArray *keys;
#end
And the implementation file, for viewDidLoad:
NSArray *arrayTemporary1 = [[NSArray alloc]initWithObjects:#"Settings 1",#"Setting 2",#"Setting 3",#"Setting 4",nil];
NSArray *arrayTemporary2 = [[NSArray alloc]initWithObjects:#"Enable Gestures",nil];
NSArray *arrayTemporary3 = [[NSArray alloc]initWithObjects:#"Instructions",#"Frequently Asked Questions",#"About",nil];
NSDictionary *temporary =[[NSDictionary alloc]initWithObjectsAndKeys:arrayTemporary1,#"Settings",arrayTemporary2,#"Application",arrayTemporary3,#"Information",nil];
self.tableContents = temporary;
self.keys = [self.tableContents allKeys];
[temporary release];
[arrayTemporary1 release];
[arrayTemporary2 release];
[arrayTemporary3 release];
Individual cell data is accessed from an array NSArray *listData =[self.tableContents objectForKey:[self.keys objectAtIndex:[indexPath section]]]; inside the cellForRowAtIndexPath method.
Whilst this works fine, the issue I'm having is that rather than displaying the sections in the order that it is written in temporary, it does so randomly. Would appreciate some guidance.
Dictionaries do not guarantee ordering, so tableContents has no memory of the order in which you added the arrays to it. You should keep ordered data in NSArrays.
Put the titles of the sections in a separate NSArray. Then use the dictionary you have to look up the data for the cells when you need to. This lets you keep the titles in the order you want, and still have a way to find the values in the dictionary.
I have no idea where this code is wrong. Please help, it is supposed to read a value from a dictionary and I use the value to call an image. I've tried to read the value as label.text but I got no result.
The only one I can call is from the nslog.
for (id key1 in dictionary)
{
NSMutableString *textnamed = [dictionary objectForKey:key1];
NSMutableString *imageDisplay =[NSMutableString stringWithFormat:#"%#.png",[dictionary objectForKey:key1]];
eyeImageSaved.image = [UIImage imageNamed:imageDisplay];
labelSaved.text = textnamed;
NSLog(#"%#",textnamed);
}
There are a few issues with your code. First of all, you should consider using NSString instead of NSMutableString because it should be faster. Second, why are you putting the dictionary object in a string then calling the dictionary object again in the next line? That first line is unnecessary. It's entirely possible that the dictionary entry is not a string, and that is why you are having issues. You should write it like this NSString *textnamed = (NSString *)[dictionary objectForKey:key1]. Also, imageNamed can only be used for files in the file bundle. Are you sure those pictures are stored there? There are a few other issues you could be having. What exactly is going wrong here?
I solved my problem. There is nothing wrong with my code above, the mistake I made is that the object that is supposed to hold my variable and store in plist as the name of the image became null. So I added the object to appdelegate.h as seen below:
AppDelegate
#interface AppDelegate : UIResponder <UIApplicationDelegate>
{
NSString *imageNameHolder;
}
#property (retain, nonatomic) NSString *StorageDecider;
View Controller
- (IBAction)lips2:(id)sender {
imageNameHolder = #"lips_blue";
}
-(void)writeNewPlist
{
AppDelegate* ref = (AppDelegate*) [[UIApplication sharedApplication] delegate];
[dictionary setObject:imageNameHolder forKey:#"image1"];
[dictionary writeToFile:finalPath atomically:YES];
}
nameDataFormArray_ & imageDataFormArray_ are NSMutableArray. Both have string and find image as per string (name of image).
- (void)readInfoFromThePlist
{
NSString* PListPath=[[NSBundle mainBundle] pathForResource:#"dataList" ofType:#"plist"];
NSMutableArray* tempDataList=[[NSMutableArray alloc ] initWithContentsOfFile:PListPath];
for(NSDictionary *dataDict in tempDataList)
{
[nameDataFormArray_ addObject:[dataDict objectForKey:#"name"]];
[imageDataFormArray_ addObject:[dataDict objectForKey:#"imagepath"]];
}
[tempDataList release];
}
I'm trying to load a simple plist file in XCode 4 for an iPad application. The goal being that it will be loaded into the table portion of a split-view.
My project structure and plist look as follows:
I then declare an array in the interface of the RootViewController:
#import <UIKit/UIKit.h>
#class DetailViewController;
#interface RootViewController : UITableViewController {
NSArray *sites;
}
#property (nonatomic, retain) IBOutlet DetailViewController *detailViewController;
#end
I then, on viewDidLoad, attempt to load in the plist:
- (void)viewDidLoad
{
[super viewDidLoad];
self.clearsSelectionOnViewWillAppear = NO;
self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
NSBundle *bundle = [NSBundle mainBundle];
//NSLog(bundle);
NSString *path = [bundle pathForResource:#"StoredSites" ofType:#"plist"];
NSLog(path);
sites = [[NSArray alloc] initWithContentsOfFile:path];
NSLog(#"%d", [sites count]);
}
The NSLog statements first return what appears to be the valid path, but upon try to load the NSArray with the contents of the file, it comes back with a count of 0:
I checked in the build phases to see if the file reference appears, and it seems to be ok:
I know this must be a simple problem, but for some reason I'm not seeing what's missing!
I appreciate the help -
You may want to using an NSDictionary, as that is what the sample code given here for the method pathForResource:ofType: uses.
I'm not entirely sure why it isn't working with an NSArray, but maybe the plist isn't formatted entirely correctly? The documentation for NSArray says that initWithContentsOfFile: takes in as a parameter quote:
The path to a file containing a string representation of an array
produced by the writeToFile:atomically: method.
Again, I'm not really sure. Hope that Helps!
The problem was the plist XML was wrapped in a dictionary rather than just being a simple array of arrays -
DShah covers it here: plist in xcode creation problem
I'm sure I'm missing something obvious here in a simple iPhone program I'm trying to write, but the code seems so basic that I can't see what's wrong.
I'm trying to use an NSMutableDictionary to store a list of classes and their associated save file names. In the header file I declare the dictionary
#interface ClassList : UITableViewController {
NSString *homedirectory;
NSString *masterindexpath;
NSMutableDictionary *classFilenameGlossary;
NSMutableArray *listofclasses;
}
#property (retain, nonatomic) NSString *homedirectory;
#property (retain, nonatomic) NSString *masterindexpath;
#property (retain, nonatomic) NSMutableDictionary *classFilenameGlossary;
#property (retain, nonatomic) NSMutableArray *listofclasses;
And, of course, in the implementation file:
#implementation ClassList
#synthesize homedirectory;
#synthesize masterindexpath;
#synthesize classFilenameGlossary;
#synthesize listofclasses;
I initialize this dictionary at ViewDidLoad from an existing file that saves the classlist:
- (void)viewDidLoad {
[super viewDidLoad];
// Get home directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
homedirectory = [paths objectAtIndex:0];
masterindexpath = [homedirectory stringByAppendingPathComponent:#"MasterIndex"];
// Get master course list or create it if necessary
NSFileManager *fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:masterindexpath] == NO)
{
NSMutableDictionary *temporarydictionary = [NSMutableDictionary dictionary];
[temporarydictionary writeToFile:masterindexpath atomically:NO];
[temporarydictionary release];
}
[classFilenameGlossary initWithContentsOfFile:masterindexpath];
[homedirectory retain];
[masterindexpath retain];
}
Later, I add an item using setObject:forKey: but the dictionary never changes. Originally I was doing this in another view controller using a pointer back to this ClassList file, but once I discovered that didn't work, I simplified and tried to just set any sample object and key within the ClassList file:
[classFilenameGlossary setObject:#"sample filename" forKey:#"sample classname"];
I've looked at the debugger variable list and it shows classFilenameGlossary properly identified as an NSMutableDictionary with 0 key/value pairs. I'm not getting any sort of error; the dictionary simply never changes. At the moment, the dictionary loaded from the file masterindexpath is empty (since I haven't been able to add any items yet), but that shouldn't keep me from being able to add items to the dictionary.
I'm a total beginner at iPhone programming, so I'm sure there's something basic that I'm missing. I'd appreciate any help.
This line:
[classFilenameGlossary initWithContentsOfFile:masterindexpath];
should look like this:
classFilenameGlossary = [[NSMutableDictionary alloc] initWithContentsOfFile:masterindexpath];
You forgot to allocate memory for the NSMutableDictionary, so that's why it never initializes.