The thing is. i want to display the each object to the tableview not it's under subs so in this case. 123.
i can't seem to figured out how to display the that one item...
also. the way it saves the plist now it overwrites the plist it seems. since it's fresh created each time i go add
i followed numbers torturials on the web and here on stack overflow. but none seem to get close to what i want to do.
MainTableViewController.h
{
NSMutableDictionary *arrayD;
}
MainTableViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
// Property List.plist code
//Gets paths from root direcory.
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
//Get documents path.
NSString *documentsPath = [paths objectAtIndex:0];
//Get the path to our PList file.
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"Servers.plist"];
//Check to see if Property List.plist exists in documents.
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]){
[[NSFileManager defaultManager]copyItemAtPath:[[NSBundle mainBundle]pathForResource:#"Servers" ofType:#"plist"] toPath:plistPath error:nil];
//If not in documents, get property list from main bundle.
// plistPath = [[NSBundle mainBundle] pathForResource:#"Servers" ofType:#"plist"];
}
//Read property list into memory as an NSData object.
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSString *errorDesc = nil;
NSPropertyListFormat format;
//convert static property list into dictionary object.
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp){
NSLog(#"Error reading plist: %#, format: %d", errorDesc, format);
}
//Display values.
NSMutableDictionary *dictinoary =[[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
tableData = [dictinoary objectForKey:#"Hostname"];
NSLog(#"Count: %i", [arrayD count]);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Hostname";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
return cell;
}
AddServerViewController.m
- (IBAction)SaveData:(id)sender {
//Get paths from root direcory.
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
//Get documents path.
NSString *documentsPath = [paths objectAtIndex:0];
//Get the path to our PList file.
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"Servers.plist"];
//Set the variables to the values in the text fields.
hostName = hostEntered.text;
portNumber = portEntered.text;
userName = userNameEntered.text;
passWord = passWordEntered.text;
NSMutableDictionary *rootObj = [NSMutableDictionary dictionaryWithCapacity:4];
NSMutableDictionary *data;
data = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects: hostName, portNumber, userName, passWord, nil] forKeys:[NSArray arrayWithObjects:#"Hostname", #"Port", #"Username", #"Password", nil]];
[rootObj setObject:data forKey:hostName];
NSString *error = nil;
//Create NSData from dictionary.
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:rootObj format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
//Check is plistData exists.
if(plistData){
//Write plistData to our Properity List.plist file.
[plistData writeToFile:plistPath atomically:YES];
}
else{
NSLog(#"Error in saveData: %#", error);
}
}
Each dictionary has allKeys method that returns an array with... all keys.
If you do what Peter said and then you can just populate your tableView with allKeys
Forgive me if I misread your question but the following was done after recreating your plist:
NSString *path = [[NSBundle mainBundle] pathForResource:#"Sample List" ofType:#"plist"];
NSDictionary *plistDict = [NSDictionary dictionaryWithContentsOfFile:path];
NSLog(#"Plist dict %#", [plistDict objectForKey:#"123"]);
That would output:
Plist dict {
Hostname = 123;
Password = 123;
Port = 123;
Username = 123;
}
Is that what you were looking for? If not, ill need a bit more detail with regards to what it is that you're looking for.
Related
I have a code to get the data of a plist file and a code to write data to a plist file. Now the things is, that it add's the readed data in one array (See images).
I want it in different arrays (See green image)
HERE IS MY CODE:
- (void)WriteData {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"MuziekList.plist"];
if ([fileManager fileExistsAtPath:path] == NO) {
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:#"MuziekList" ofType:#"plist"];
[fileManager copyItemAtPath:resourcePath toPath:path error:&error];
}
//_______________________________________________________________________________________________________________
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//load from savedStock example int value
NSArray *NummerTexts;
NummerTexts = [savedStock objectForKey:#"Nummers"];
NSString *NummerTextsR = [[NummerTexts valueForKey:#"description"] componentsJoinedByString:#" - "];
NSArray *ArtiestTexts;
ArtiestTexts = [savedStock objectForKey:#"Artiesten"];
NSString *ArtiestTextsR = [[ArtiestTexts valueForKey:#"description"] componentsJoinedByString:#" - "];
//_______________________________________________________________________________________________________________
NSUserDefaults *CurrentVideoNummerResult = [NSUserDefaults standardUserDefaults];
NSString *CurrentVideoNummer = [CurrentVideoNummerResult stringForKey:#"CurrentVideoNummer"];
NSUserDefaults *CurrentVideoArtiestResult = [NSUserDefaults standardUserDefaults];
NSString *CurrentVideoArtiest = [CurrentVideoArtiestResult stringForKey:#"CurrentVideoArtiest"];
/*
NSUserDefaults *CurrentVideoIDResult = [NSUserDefaults standardUserDefaults];
NSString *CurrentVideoID = [CurrentVideoIDResult stringForKey:#"CurrentVideoID"];
*/
NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy];
NSMutableArray *newArray = [[NSMutableArray alloc] init];
NSMutableArray *newArray2 = [[NSMutableArray alloc] init];
newArray = [NSMutableArray arrayWithObjects:CurrentVideoNummer, NummerTextsR, nil];
[plist setObject:newArray forKey:#"Nummers"];
newArray2 = [NSMutableArray arrayWithObjects:CurrentVideoArtiest, ArtiestTextsR, nil];
[plist setObject:newArray2 forKey:#"Artiesten"];
[plist writeToFile:path atomically:YES];
}
Click link for images
https://www.dropbox.com/sh/wrk8h8cnwye8myx/AADl4omkGdl3S4ESXv6NbymVa?dl=0
Your question and problem are confusing. Maybe this will help:
Your code reads your current array (NummerTexts), flattens that array to a single string (NummerTextsR), gets a second string (CurrentVideoNummer), then builds a two-element array (newArray).
Your question appears to be why do you get a two-element array...?
If you don't want to flatten your original array don't do so, just make a mutable copy of it, something like:
NSMutableArray *existingTexts = [[NummerTexts valueForKey:#"description"] mutableCopy];
add your new element:
[existingTexts addObject:currentVideoNummer];
and write it back like you already are.
HTH
BTW Do not start local variable names with an uppercase letter, this goes against convention and is why the syntax highlighting in your question is all wrong.
My question in UIActionSheet button add to favourite click and copy UITableViewCell in nextview so i am using string value in store dynamic create plist file and first time click cell and open UIActionSheet and add to favourite UIButton click and copy 1 cell properly but second time add to favourite click and not add 2 item store only 1 new array item so my question in plist file at a time 1 value is add so any answer..`
Store data from plist
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex ==2) {
FavoritesViewController *objfav= [self.storyboard instantiateViewControllerWithIdentifier:#"fav"];
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"manuallyData.plist"];
[arrplist addObject:quote];
NSDictionary *plistDict = [[NSDictionary alloc] initWithObjects: [NSArray arrayWithObjects: arrplist, nil] forKeys: [NSArray arrayWithObjects: #"icon", nil]];
NSString *error = nil;
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
if(plistData)
{
[plistData writeToFile:plistPath atomically:YES];
}
else
{
}
objfav.arrCopy = arrplist;
[self.navigationController pushViewController:objfav animated:YES];
}
}
fetch data from dynamic create plist file in nextview
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"manuallyData.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
{
plistPath = [[NSBundle mainBundle] pathForResource:#"manuallyData" ofType:#"plist"];
}
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
arrCopy = [dict objectForKey:#"icon"];
I am trying to fetch Images which i am storing in directory which i have shown in below code . I have tried a lot in StachOverFlow And Chats but not able to achieve the task . Actually i want to generate array of images from the array of filePath which are storing the path of images . Which i will show in UICollectionView . Please check my code and tell me what all can be done to achieve the needed . Thanks in advance
I have array of filepath already generated , i just want to fetch images from them and show it in grid view
-(void)plistRender{
// get paths from root direcory
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:#"PhotoBucket.plist"];
//pngDATA.....
NSString *totalName = [NSString stringWithFormat:#"EGK_%# ", [NSDate date]];
PhotodocumentsPath = [paths objectAtIndex:0];
PhotofilePath = [PhotodocumentsPath stringByAppendingPathComponent:totalName]; //Add the file name
NSData *pngData = UIImagePNGRepresentation(printingImage);
//Write image to the file directory .............
[pngData writeToFile:[self documentsPathForFileName:PhotofilePath] atomically:YES];
[photos_URL addObject:PhotofilePath];
[photos addObject:totalName];
[grid_copy addObject:[NSNumber numberWithInteger:count]];
[grids addObject:whichProduct];
[Totalamount addObject:[NSNumber numberWithInteger:amt]];
NSDictionary *plistDictionary = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: photos,grids,grid_copy,Totalamount,nil] forKeys:[NSArray arrayWithObjects: #"Photo_URL",#"Product",#"Copy",#"Amount", nil]];
NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDictionary format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
// check is plistData exists
if(plistData)
{
// write plistData to our Data.plist file
[plistData writeToFile:plistPath atomically:YES];
}
else
{
NSLog(#"Error in saveData: %#", error);
}
NSString *string = [[NSString alloc] initWithData:plistData encoding:NSUTF8StringEncoding];
NSLog(#" plist Data %#", string);
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"PhotoBucket"]){
RecipeCollectionViewController *photoBucket = [segue destinationViewController];
NSLog(#"Prepare Segue%#",photoBucket.photoCollection);
NSLog(#"Number of photos %#",photos_URL);
NSMutableArray *imgQueue = [[NSMutableArray alloc] initWithCapacity:photos_URL.count];
for (NSString* path in photos_URL) {
[imgQueue addObject:[UIImage imageWithContentsOfFile:path]];
}
photoBucket.photoCollection = imgQueue;
}
}
try this
for(int i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
if ([[strFilePath pathExtension] isEqualToString:#"jpg"] || [[strFilePath pathExtension] isEqualToString:#"png"] || [[strFilePath pathExtension] isEqualToString:#"PNG"])
{
NSString *imagePath = [[stringPath stringByAppendingFormat:#"/"] stringByAppendingFormat:strFilePath];
NSData *data = [NSData dataWithContentsOfFile:imagePath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
}
}
}
Hi you can fetch like this:
NSArray *pathPlist1 =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryStr1 = [pathPlist1 objectAtIndex:0];
NSString *plistLocation1 =
[documentsDirectoryStr1 stringByAppendingPathComponent:#"ImageStorage"];
NSFileManager *filemgr;
NSArray *filelist;
int i;
filemgr =[NSFileManager defaultManager];
filelist = [filemgr contentsOfDirectoryAtPath:plistLocation1 error:NULL];
NSLog(#"filelist =%lu",[filelist count]);
cacheImagesArray=[[NSMutableArray alloc] init];
cacheImagesDataArray=[[NSMutableArray alloc] init];
for (i = 0; i < [filelist count]; i++){
NSLog(#"%#", [filelist objectAtIndex: i]);
NSString *imageName=[NSString stringWithFormat:#"%#",[filelist objectAtIndex: i]];
NSString *path=[NSString stringWithFormat:#"%#/%#",plistLocation1, [filelist objectAtIndex: i]];
NSLog(#"Path is =%#",path);
NSData* data = [NSData dataWithContentsOfFile:path];
[cacheImagesDataArray addObject:data];
[cacheImagesArray addObject:imageName];
}
thanks
This question already has answers here:
How to Save NSMutableArray into plist in iphone
(4 answers)
Closed 9 years ago.
I have NSMutableArray with name "add" that has in self name of cell (in UITableView)
I want store this "add" NSMutableArray in .plist file.
this is "add" code:
//NSArray *NaMe;
//NSMutableArray *add;
//NSMutableArray *all;
for (int i =0; i<11; i++) {
NSIndexPath *indexPath = [self.Table indexPathForSelectedRow];
NaMe = [[all objectAtIndex:(indexPath.row)+i]objectForKey:#"name"];
if(!add){
add = [NSMutableArray array];
}
[add addObject:NaMe];
}
NSLog(#"%#",add);
this add show me name of cell and I want store this name in .plist file.
I assume you want to save the plist for persistence.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = paths[0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Names.plist"];
[add writeToFile:filePath atomically:YES];
To read back from plist
NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
NSArray*pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*pListdocumentsDirectory = [pListpathsobjectAtIndex:0];
NSString*pListpath = [pListdocumentsDirectory stringByAppendingPathComponent:#"Apps.plist"]; NSFileManager*pListfileMgr = [NSFileManager defaultManager];
//Create a plist if it doesn't alread exist
if (![pListfileMgrfileExistsAtPath: pListpath])
{
NSString*bundle = [[NSBundle mainBundle]pathForResource:#"Apps" ofType:#"plist"];
[pListfileMgrcopyItemAtPath:bundletoPath: pListpatherror:&error];
}
//Write to the plist
NSMutableDictionary*thePList = [[NSMutableDictionary alloc] initWithContentsOfFile: pListpath];
[thePList setObject:[NSString stringWithFormat:#"YourContent"] forKey:#"Related Key"];
[thePList writeToFile: pListpathatomically: YES];
Try This Sample Code
The solution is quite simple.
Create an NSArray containing your NSMutableArray, then write it to a path.
NSArray *yourArray=[NSArray arrayWithObjects:<#(id), ...#>, nil];
NSArray *yourPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libDir = [yourPath objectAtIndex:0];
NSString *loc = [libDir stringByAppendingString:#"/anyfilename.plist"];
[yourArray writeToFile:loc atomically:YES];
Fetch your array using:
yourPath = [bundle pathForResource:#"anyfilename" ofType:#"plist"];
yourArray = (yourArray!= nil ? [NSArray arrayWithContentsOfFile:loc] : nil);
user this code
#define DOC_DIR [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
NSArray *NaMe;
NSMutableArray *add;
NSMutableArray *all;
for (int i =0; i<11; i++) {
NSIndexPath *indexPath = [self.Table indexPathForSelectedRow];
NaMe = [[all objectAtIndex:(indexPath.row)+i]objectForKey:#"name"];
if(!add){
add = [NSMutableArray array];
}
[add addObject:NaMe];
}
NSLog(#"%#",add);
[self writeDataToPlistFromArray:add];
-(void) writeDataToPlistFromArray:(NSArray *) dataArray
{
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:dataArray,#"Root", nil];
NSString *path = [DOC_DIR stringByAppendingPathComponent:#"Names.plist"];
[dic writeToFile:path atomically:YES];
}
I have a .plist file which have this structure,
I want to add or replace the Item 5. I am using this code
NSError *error ;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Introduction.plist"];
NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSString *comment = str;
[data replaceObjectAtIndex:1 withObject:comment];
[data writeToFile:path atomically:YES];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:path]) {
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"Introduction" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath:path error:&error];
}
If I change replaceObjectAtIndex: to 5 it changes my plist structure, and I don't want that.
How can I insert/replace the text at the row 5 (Item 5) of particular Index?
You structure has an array of arrays.
[data replaceObjectAtIndex:1 withObject:comment];
By this code you are replacing an array at index 1 with a string. Do you specifically need to insert to 5th index or do you just need to add it to existing sub array?
NSMutableArray *subArray = [data[sectionIndex] mutableCopy];
if (!subArray) {
subArray = [NSMutableArray array];
}
if (rowIndex<[subArray count]) {
[subArray replaceObjectAtIndex:rowIndex withObject:comment];
}else{
[subArray addObject:comment];
}
[data replaceObjectAtIndex:sectionIndex withObject:subArray];
[data writeToFile:path atomically:NO];
Access the subArray, make it mutable and add or insert at specific index. If you are trying to insert don't forget to include a check if the index is not greater than count of that array.