I'm a newbie to Objective-C so any help is greatly appreciated.
I have a TableView that is successfully pulling back the list from my Data.plist file within my Xcode project but I need it to pull from the Documents Directory.
I have seen many posts about this but can't seem to get it to work for me.
Here is my .m file below. Like I said, it pulls back the data but I need it to be dynamically changed based on my Documents plist copy.
Thanks in advance!
#synthesize content = _content;
- (NSArray *)content
{
if (!_content) {
_content = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"]];
}
return _content;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.content count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text = [[self.content objectAtIndex:indexPath.row] valueForKey:#"Name"];
cell.detailTextLabel.text = [[self.content objectAtIndex:indexPath.row] valueForKey:#"Score"];
return cell;
}
Try this:
Step 1: In .h File declare a global variable
#property (nonatomic,retain) NSMutableDictionary *contents;
Step 2: In .m file set synthesis.
#synthesize contents;
Step 3: Move plist file from mainbudle into documents directory
-(void) createPlistDocuments
{
// Get path to documents directory
NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// Finds the contained Documents directory
NSString *documentsDirectory = [arrayPaths objectAtIndex:0];
NSError *error;
// Create an object that we will later use to look for a file and return a boolean value on whether or not it exists
NSFileManager *manager = [NSFileManager defaultManager];
// File we want to move, stored in original top level directory
NSString *demoFile = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"plist"];
// Define where we want it moved to and name it
NSString *demoFileMoved = [NSString stringWithFormat:#"%#/data.plist", documentsDirectory];
// Attempt the copy
if ([manager copyItemAtPath:demoFile toPath:demoFileMoved error:&error] != YES)
NSLog(#"Unable to move file: %#", [error localizedDescription]);
}
Step 4: Read plist data from document directory
- (void)viewDidLoad
{
[super viewDidLoad];
[self createPlistDocuments];
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [NSString stringWithFormat:#"%#/data.plist",documentsDirectoryPath];
contents = [NSArray arrayWithContentsOfFile:path];
NSLog(#"%d", contents.count);
}
For brief explanation follow this sample... TechDevMobile(IOS-Message-Chat)
Related
I have a tableview that the rows are been filled with the name of .csv files that are in the document directory, i need to open the .csv that is been selected in the row and then show the info in a detail view. I'm trying to get the indexPath.row that it's been selected to get the correct element in the array but is crashing here's is that part of the code and above i will post the full code:
-(UITableViewCell *)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%d", indexPath.row);
currentcsvfile = [dirList objectAtIndex:indexPath.row ];;
NSLog(#"\n current csv %#",currentcsvfile);
[self performSegueWithIdentifier:#"detailsegue" sender:self];
}
This is the error:
2017-10-09 22:51:31.590248 oFiOSstoryboard[2340:583894] 2
2017-10-09 22:51:31.590460 oFiOSstoryboard[2340:583894] *** -[__NSArrayI objectAtIndex:]: message sent to deallocated instance 0x170246540
![error
]1
Here is the full code:
#import "CameraViewController.h"
#import "resultsDetailView.h"
#interface CameraViewController ()
#property (strong, nonatomic) IBOutlet UITableView *data;
#property (retain, nonatomic) IBOutlet UILabel *timeStamp;
#end
////////////////////////csv readder
NSMutableArray *tableDataArray;
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSFileManager *manager = [NSFileManager defaultManager];
NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:bundleRoot];
NSString *filename;
NSMutableArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *strPath = [[NSBundle mainBundle] pathForResource:#"file" ofType:#"csv"];
NSString *strFile = [NSString stringWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil];
NSMutableArray *timeStampb = [[NSMutableArray alloc] init]; ;
NSMutableArray *arrayToDelete = [[NSMutableArray alloc] init]; ;
NSMutableArray *filePathsArray ;
NSMutableArray *dirList= [[NSMutableArray alloc] init]; ;
NSString *currentcsvfile;
#implementation CameraViewController
#synthesize data;
- (void)viewDidLoad {
[super viewDidLoad];
// ////lista de documentos
self.data.scrollEnabled = YES;
self.data.delegate = self;
self.data.dataSource = self;
filePathsArray =[[NSMutableArray alloc] init]; ;
NSMutableArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
NSMutableArray* fileList = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
//--- Listing file by name sort
NSLog(#"\n File list %#",fileList);
//---- Sorting files by extension
NSMutableArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF EndsWith '.csv'"];
filePathsArray = [filePathsArray filteredArrayUsingPredicate:predicate];
NSLog(#"\n\n Sorted files by extension %#",filePathsArray);
dirList = filePathsArray;
NSString *docPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
if (!strFile) {
NSLog(#"Error reading file.");
}
[timeStampb release];
timeStampb = [[NSMutableArray alloc] initWithArray:[strFile componentsSeparatedByString:#"\,"]];
// this .csv file is seperated with new line character
// if .csv is seperated by comma use "," instesd of "\n"
for(NSString *countryname in timeStampb) {
NSLog(#"%#", timeStampb);
}
}
////////////////////////////////////////////////////////////////Delete csv files
//- (IBAction)delet:(id)sender {
// NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
//
// NSString *filePath = [docPath stringByAppendingPathComponent:#"jorge.csv"];
// NSError *error = nil;
// [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
//}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
# pragma – mark table view DataSource Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dirList count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier ];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
UIColor* color = [UIColor colorWithRed:(254.0/255.0) green:(251.0/255.0) blue:(248.0/255.0) alpha:1];
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor colorWithRed:(253.0/255.0) green:(0.0/255.0) blue:(237.0/255.0) alpha:1];
[cell setSelectedBackgroundView:bgColorView];
cell.backgroundColor = color;
}
cell.textLabel.text = [timeStampb objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [dirList objectAtIndex:indexPath.row];
cell.textLabel.textColor = [UIColor colorWithRed:(0.0/255.0) green:(0.0/255.0) blue:(0.0/255.0) alpha:1];
cell.textLabel.font=[UIFont systemFontOfSize:8.0];
cell.detailTextLabel.font=[UIFont systemFontOfSize:15.0];
cell.detailTextLabel.textColor = [UIColor colorWithRed:(235.0/255.0) green:(120.0/255.0) blue:(33.0/255.0) alpha:1];
return cell;
}
-(UITableViewCell *)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%d", indexPath.row); // you can see selected row number in your console;
currentcsvfile = [dirList objectAtIndex:indexPath.row ];;
NSLog(#"\n current csv %#",currentcsvfile);
[self performSegueWithIdentifier:#"detailsegue" sender:self];
}
- (IBAction)deleteRow:(id)sender {
//we are not in edit mode yet
if([self.data isEditing] == NO){
//up the button so that the user knows to click it when they
//are done
[self.data setTitle:#"Done"];
//set the table to editing mode
[self.data setEditing:YES animated:YES];
}else{
//we are currently in editing mode
//change the button text back to Edit
//take the table out of edit mode
[self.data setEditing:NO animated:YES];
}
}
#pragma mark – TableView delegate
- (void)dealloc {
[_timeStamp release];
[dirList release];
self.data.delegate = nil;
self.data.dataSource = nil;
[super dealloc];
}
#end
When you get the array back from the file manager, retain it.
Also, there's no need for filePathsArray =[[NSMutableArray alloc] init]; ; since you are about to overwrite it with the returned results.
At line
dirList = filePathsArray;
You put autorelease object into variable ‘dirList’. Also you have a memory leak here.
If you need to put any objects from one array to other, use method addObjectsFromArray:. If you need to put other array into variable, use release/retain routine (Memory management in Objective-C)
New to coding and trying to create a simple check list (like a shopping list) for part of my iOS programme. Selecting a cell changes the accessory icon ok and changing the BOOL value in the dictionary manually before running the simulator also changes the acc' icon fine. So the problem seems to be with the code for altering the BOOL value in the plist after a cell is selected. Any help would massively appreciated. As I said pretty new to it so apologies for any shoddy code or obvious mistakes.
*CODE EDITED SO NO LONGER READING AND WRITING LIST FROM MAIN BUNDLE
#import "CheckListViewController.h"
#import "ListItem.h"
#interface CheckListViewController ()
#end
#implementation CheckListViewController
{
NSMutableArray *eventList;
}
#synthesize tableView = _tableView;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* dataPath = [documentsDirectory stringByAppendingPathComponent:#"CheckList.plist"];
if ( ![[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
NSString* resourceaPath = [[NSBundle mainBundle] pathForResource:#"CheckList" ofType:#"plist"];
[[NSFileManager defaultManager] copyItemAtPath:resourceaPath toPath:dataPath error:NULL];
}
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"CheckList.plist"];
NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
ListItem *listItem1 = [ListItem new];
listItem1.itemName = #"Read Guide";
listItem1.itemSelected = [dict valueForKey:#"Read Guide"];
.....
eventList = [NSMutableArray arrayWithObjects:listItem1, listItem2, listItem3, listItem4, listItem5, listItem6, listItem7, listItem8, nil];
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//Return the number of rows in the section.
return eventList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
ListItem *listItem = [eventList objectAtIndex:indexPath.row];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
if (listItem.itemSelected == [NSNumber numberWithBool:YES]) {
(cell.accessoryType = UITableViewCellAccessoryCheckmark);
} else {
(cell.accessoryType = UITableViewCellAccessoryNone);
}
}
cell.textLabel.text = listItem.itemName;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:NO];
ListItem *listItem = [eventList objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView cellForRowAtIndexPath: indexPath];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"CheckList.plist"];
NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
if (cell.accessoryType == UITableViewCellAccessoryNone) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
// Reflect selection in data model
[dict setObject:[NSNumber numberWithBool:YES] forKey:listItem.itemSelected];
[dict writeToFile:path atomically:YES];
} else if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
// Reflect deselection in data model
[dict setObject:[NSNumber numberWithBool:NO] forKey:listItem.itemSelected];
[dict writeToFile:path atomically:YES];
}
}
#end
Sorry for the massive chunk of code but thought any of it could potentially be problematic.
It looks like the path you are saving to and load from are different. You are loading from a bundle path, and then saving to a relative path with writeToFile:atomically. If my guess is correct, the default path for that method is not back into the bundle, but the documents directory of the app. On iOS, you cannot write back to the main bundle, so there a very good chance the file is not being saved where you think it is.
I would want to show all the pictures in my directory however I am creating Folders in the Directory so that I can sort the pictures. I want to show all of the pictures in several folders. I am using the code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
allImagesArray = [[NSMutableArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *location=#"Bottoms"#"Top"#"Right"#"Left"#"Down"#"Up";
NSString *fPath = [documentsDirectory stringByAppendingPathComponent:location];
NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath: fPath];
collectionTrash.delegate =self;
collectionTrash.dataSource=self;
for(NSString *str in directoryContent){
NSLog(#"i");
NSString *finalFilePath = [fPath stringByAppendingPathComponent:str];
NSData *data = [NSData dataWithContentsOfFile:finalFilePath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
[allImagesArray addObject:image];
NSLog(#"array:%#",[allImagesArray description]);
}}}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
NSLog(#"j");
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [allImagesArray count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *reuseID = #"ReuseID";
TrashCell *mycell = (TrashCell *) [collectionView dequeueReusableCellWithReuseIdentifier:reuseID forIndexPath:indexPath];
UIImageView *imageInCell = (UIImageView*)[mycell viewWithTag:1];
imageInCell.image = [allImagesArray objectAtIndex:indexPath.row];
NSLog(#"a");
return mycell;
}
If you see my code you can notice that I have put NSLOG i and j. The j comes up but the i does not.... Is my way wrong showing all the pictures that are in several folders? I do not have any error.
If you have multiple folders then you need to iterate over the folders and then the folder contents to process all of it.
While this line:
NSString *location=#"Bottoms"#"Top"#"Right"#"Left"#"Down"#"Up";
Is technically legal, I guess you're thinking it will do some array / iteration thing for you. It won't. It just concatenates all of the strings together. You probably want something more like:
NSArray *locations = #[ #"Bottoms", #"Top", #"Right", #"Left", #"Down", #"Up" ];
Then you can run a loop over the folders and then the contents:
for(NSString *folder in locations) {
// get the folder contents
for(NSString *file in directoryContent) {
// load the image
}
}
Firstly = I apologize because I have already tried to ask this once before here
I am really struggling with this:
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// Delete the row from the data source.
[_mainTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
By using the code above I know it is possible to delete an entry from an array that is displayed in a UITableView. However I am wanting to delete files form my Documents Directory that are downloaded by the user and no longer required.
Now I in the mean time and after more searching this code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *file = [[NSString alloc] init];
for(int i=0; i<[paths count]; i++)
{
file = [documentsDirectoryPath stringByAppendingFormat:#"/%#",_fileArray];
NSLog(#"%#", file);
}
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:file error:NULL];
Allows me to list all the files that are in the array in my console and this code:
- (void)removeFile:(NSString*)fileName {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.mp3", fileName]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
}
together with: [self removeFile: _filename]; allows me to delete a specific file.
so I am making head way. But I am really stuck when it comes to a user being able to swipe and delete a file. Of Course I do not know what file is going to be in the directory.
Secondly - How do I handle being able to load the tableView once all the files are deleted?
If I do that using this code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] > 0)
{
NSLog(#"Path: %#", [paths objectAtIndex:0]);
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
// Remove Documents directory and all the files
BOOL deleted = [fileManager removeItemAtPath:[paths objectAtIndex:0] error:&error];
}
I get the an termination error - I think that is because the directory has also been removed.
I know there is a bit of code here, but I really hope someone and guide me through this:-)
If i correctly understood, you want step by step guide.
Lets consider that you have a working UITableView (mainTableView) that take data from NSMutableArray (mainArray).
This will return document directory path.
-(NSString*)filePath{
NSString *path=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSLog(#"%#",path);
return path;
}
Somewhere we need to init array ,i did it on viewDidLoad.
- (void)viewDidLoad
{
[super viewDidLoad];
mainDataArray=[[NSMutableArray alloc]init];
[self loadContentsOfDirectory:[self filePath]];
}
//here i am adding names of files from documents directory
-(void)loadContentsOfDirectory:(NSString*)path
{
NSError *error=nil;
NSArray *pathArray=[[NSFileManager defaultManager]contentsOfDirectoryAtPath:path error:&error];
if (error) {
NSLog(#"ERROR: %#",error);
}else{
if (pathArray) {
[mainDataArray removeAllObjects];
[mainDataArray addObjectsFromArray:pathArray];
}
}
}
#pragma mark UITableView_Methods
//delete file then if file is deleted , remove filename from array and remove cell
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
NSString *fileName=[mainDataArray objectAtIndex:indexPath.row];
NSError *error=nil;
NSString *pathToDelete=[[self filePath]stringByAppendingPathComponent:fileName];
BOOL succes=[[NSFileManager defaultManager]removeItemAtPath:pathToDelete error:&error];
if (error) {
NSLog(#"ERROR: %#",error);
}
// if file is succes deleted
if (succes) {
//remove this item from array
[mainDataArray removeObject:fileName];
//and remove cell
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}else{
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:#"Alert!" message:#"File can not be deleted" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alertView show];
}
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [mainDataArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *reusableCell=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:reusableCell];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusableCell];
}
cell.textLabel.text=[mainDataArray objectAtIndex:indexPath.row];
return cell;
}
I think your error is that you do not remove something maybe cell, object in array.
Hope this will help.
If you want to delete selected files from your Documents directory then.
First you have to get all files from Documents directory of your app like this
-(NSArray *)listFileAtPath:(NSString *)path
{
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];
return directoryContent;
}
Then use return array from above function to display files to UITableView
NSArray *filesArray = [self listFileAtPath:documentDirectoryPath];
And finally when you delete selected files then you have to remove that file from Documents directory and also from filesArray for managing UITableView something like this:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// Delete the row from the data source.
[_mainTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
// Remove file from document directory
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL deleted = [fileManager removeItemAtPath:[paths objectAtIndex:0] error:&error];
// Remove file entry from filesArray
[filesArray removeObjectAtIndex:indexPath.row];
}
}
Hope will help you if you want to do something like this.
Hi I always seem to get exception when I use objectAtInded method to retrieve NSString from an array. I am reading data from a dictionary which is in the "PropertyList.plist" file.My code is
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:#"PropertyList"
ofType:#"plist"];
names = [[NSDictionary alloc]
initWithContentsOfFile:path];
keys = [[[names allKeys] sortedArrayUsingSelector:
#selector(compare:)] retain];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [names objectForKey:key];
static NSString *SectionsTableIdentifier = #"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
if(cell == nil)
{
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SectionsTableIdentifier] autorelease];
}
cell.textLabel.text = [nameSection objectAtIndex:row];
return cell;
}
The exception happens on the method "cellForRowAtIndexPath" in the line
cell.textLabel.text = [nameSection objectAtIndex:row];
The error message is
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6832440
The plist file is
Where ever I use "[nameSection objectAtIndex:row];" type of statement it always get exception.
The reason for this can be following
[names objectForKey:key];. This statement could give output a NSMutableDictionary type and you are taking a NSArray from that. OR
If it is an array then use the below code for getting the nameSection
NSMutableArray *nameSection = (NSMutableArray*)[names objectForKey:key];
// using (NSMutableArray*) before the code is for external typecasting to tell the compiler that the output is of NSMutableArray type.
Hope this helps.
EDIT:-
use the method below to get your dictionary from the plist file
-(NSMutableDictionary *) GetDictDataFromPlistFile:(NSString *) fileName
{
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",fileName]]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:fileName ofType:#"plist"]; //5
[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}
NSMutableDictionary *dictData = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
return dictData;
}
Here, name contains only one key of root.
What you need for name is the value of key Root.
Please retry!
Like #scorpiozj said 'names' contains only key of 'Root'. So what I did I know is not a very good way to do it. I am sure there is some other way. I changed the 'viewDidLoad' method to this,
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:#"PropertyList"
ofType:#"plist"];
names = [[NSDictionary alloc]
initWithContentsOfFile:path];
keys = [names allKeys];
NSString *key = [keys objectAtIndex:0];
names = [names objectForKey:key];
keys = [[[names allKeys] sortedArrayUsingSelector:#selector(compare:)] retain];
NSLog(#"keys = %# names = %#",keys,names);
}
It works! Any idea how to do it better will be appreciated though.