iOS SDK, Objective-C, uitable only showing one cell - objective-c

I have a textfield that the user inputs, then I save it with NSKeyedArchiver and pull it out to view on the table but every time I enter something in the textfield and save it, it replaces the first item in the cell, I want it to add it to the table.
in NewEntry.m where I save the data with
- (IBAction)saveButton:(id)sender {
int i = selectedSegment.selectedSegmentIndex;
app = [[UIApplication sharedApplication] delegate];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setInteger:i forKey:#"category"];
if (i == 0) {
// [userDefaults setObject:titlefield.text forKey: #"titlehomework"];
// [userDefaults setObject:detailstextfield.text forKey:#"detailshomework"];
NSMutableArray *contactArray;
contactArray = [[NSMutableArray alloc] init];
[contactArray addObject:titlefield.text];
[contactArray addObject:detailstextfield.text];
[NSKeyedArchiver archiveRootObject:
contactArray toFile:datafilePath];
}
else if(selectedSegment.selectedSegmentIndex == 1) {
[userDefaults setObject:titlefield.text forKey:#"titletextprojects"];
[userDefaults setObject:detailstextfield.text forKey:#"detailsprojects"];
}
else if (selectedSegment.selectedSegmentIndex == 2){
[userDefaults setObject:titlefield.text forKey:#"titletextappointments"];
[userDefaults setObject:detailstextfield.text forKey:#"detailsappointments"];
}
else if (selectedSegment.selectedSegmentIndex == 3){
[userDefaults setObject:titlefield.text forKey:#"titletextevents"];
[userDefaults setObject:detailstextfield.text forKey:#"detailsevents"];
}
else if (selectedSegment.selectedSegmentIndex == 4){
[userDefaults setObject:titlefield.text forKey:#"titletexttodolist"];
[userDefaults setObject:detailstextfield.text forKey:#"detailstodolist"];
}
/*[userDefaults synchronize];
titlefield.text =#" ";
detailstextfield.text =#" ";
NSLog(#"selected segment %i", i);*/
/* UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Task saved!" message:#"You're all done." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, selectedSegment.selectedSegmentIndex];
[alert show];*/
[[NSNotificationCenter defaultCenter] postNotificationName:#"ValuesChanged"
object:self];
[self dismissModalViewControllerAnimated:YES];
}
NewEntry ViewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
if (__managedObjectContext == nil)
{
__managedObjectContext = [(StaticTableAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(#"After managedObjectContext_: %#", __managedObjectContext);
}
NSFileManager *filemgr;
NSString *docsDir;
NSArray *dirPaths;
filemgr = [NSFileManager defaultManager];
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the data file
datafilePath = [[NSString alloc] initWithString: [docsDir
stringByAppendingPathComponent: #"data.archive"]];
// Check if the file already exists
if ([filemgr fileExistsAtPath: datafilePath])
{
NSMutableArray *dataArray;
dataArray = [NSKeyedUnarchiver
unarchiveObjectWithFile: datafilePath];
//titlefield.text = [dataArray objectAtIndex:0];
// detailstextfield.text = [dataArray objectAtIndex:1];
}
}
new entry ViewDidUnload:
- (void)viewDidUnload
{
[self setTitleTextfield:nil];
[self setCategory:nil];
[self setDetailstextfield:nil];
[self setTitlefield:nil];
[self setTitlefield:nil];
[self setSelectedSegment:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
And in the table controller I call it here:
tableview:
- (void)viewDidLoad
{
[super viewDidLoad];
// [self fetchRecords];
if(tablesubtitles == nil && tabledata == nil){
tablesubtitles = [[NSMutableArray alloc]init];
tabledata = [[NSMutableArray alloc] init];
}
NSFileManager *filemgr;
NSString *docsDir;
NSArray *dirPaths;
filemgr = [NSFileManager defaultManager];
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the data file
datafilePath = [[NSString alloc] initWithString: [docsDir
stringByAppendingPathComponent: #"data.archive"]];
// Check if the file already exists
if ([filemgr fileExistsAtPath: datafilePath])
{
NSMutableArray *dataArray;
dataArray = [NSKeyedUnarchiver
unarchiveObjectWithFile: datafilePath];
titlestring = [dataArray objectAtIndex:0 ];
detailsstring = [dataArray objectAtIndex:1];
[tabledata addObject:titlestring];
[tablesubtitles addObject:detailsstring];
}
}
and:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
UITableViewCell *cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:#"homeworkcell"];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"homework"];
}
NSString *cellValue = [tabledata objectAtIndex:indexPath.row];
NSString *subtitle = [tablesubtitles objectAtIndex:indexPath.row];
cell.textLabel.text= cellValue;
cell.detailTextLabel.text= subtitle;
cell.textLabel.font = [UIFont systemFontOfSize:14.0];
cell.textLabel.backgroundColor = [ UIColor clearColor];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
//[tabledata addObjectser.title];
//[tabledata addObject:user.detai/s];
//static NSString *CellIdentifier = #"Cell";
// Configure the cell.
//-----------------------------------------START----------------------------Set image of cell----
cellImage = [UIImage imageNamed:#"checkboxblank.png"];
cell.imageView.image = cellImage;
//--------------------------------------------END---------------------------end set image of cell--
return cell;
}
*************UPDATE**********
So in saveButton it should be:
NSMutableArray *contactArray;
contactArray = [NSKeyedUnarchiver
unarchiveObjectWithFile: datafilePath];
// contactArray = [[NSMutableArray alloc] init];
[contactArray addObject:titlefield.text];
[contactArray addObject:detailstextfield.text];
[NSKeyedArchiver archiveRootObject:
contactArray toFile:datafilePath];
// NSDictionary *stuff;
?

The problem is that you are creating a new mutable array, putting one item in it, and then archiving that array to your file. This is going to replace whatever was there before.
To add a new item you need to unarchive the array first, add to that array, and then archive your new array.
There seems to be some core data code in here as well, there is little merit in doing your own archiving if you are going to use core data.

Related

How to pass a Dictionary data from table View to the another View Controller

I am fetching the contacts of iPhone and make their Dictionary Check my code
-(void) fetchContacts
{
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES) {
//keys with fetching properties
NSArray *keys = #[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
NSString *containerId = store.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSError *error;
NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
if (error) {
NSLog(#"error fetching contacts %#", error);
} else {
NSString *phone;
NSString *fullName;
NSString *firstName;
NSString *lastName;
UIImage *profileImage;
NSMutableArray *contactNumbersArray;
for (CNContact *contact in cnContacts) {
// copy data to my custom Contacts class.
firstName = contact.givenName;
lastName = contact.familyName;
if (lastName == nil) {
fullName=[NSString stringWithFormat:#"%#",firstName];
}else if (firstName == nil){
fullName=[NSString stringWithFormat:#"%#",lastName];
}
else{
fullName=[NSString stringWithFormat:#"%# %#",firstName,lastName];
}
UIImage *image = [UIImage imageWithData:contact.imageData];
if (image != nil) {
profileImage = image;
}else{
profileImage = [UIImage imageNamed:#"acc_sett.png "];
}
for (CNLabeledValue *label in contact.phoneNumbers) {
phone = [label.value stringValue];
if ([phone length] > 0) {
[contactNumbersArray addObject:phone];
}
}
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,#"fullName",profileImage,#"userImage",phone,#"PhoneNumbers", nil];
[_Contacts addObject:personDict];
NSLog(#"%#",phone);
NSLog(#"%#",fullName);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.contacttableview reloadData];
});
}
}
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [_Contacts count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary* personDict = [_Contacts objectAtIndex:indexPath.row];
UITableViewCell *cell = nil;
cell = [_contacttableview dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"cell"];
}
cell.imageView.image = [personDict objectForKey:#"userImage"];
cell.textLabel.text = [personDict objectForKey:#"fullName"];
cell.detailTextLabel.text = [personDict objectForKey:#"phoneNumbers"];
return cell;
}
With the help of this code Dictionary Data is display on the tableview now i want to pass image fullname and phone number of a person on the another view controller on selecting their row.
I have tried many method but not get any result
In YourViewController.h, create a property of Person that you want to pass
#property (nonatomic, assign) NSDictionary *person;
In TableViewController.m, didSelectRowAtIndexPath:
YourViewController *vc = [[YourViewController alloc] init];
vc.person = [_Contacts objectAtIndex:indexPath.row];
[self.navigationController pushViewController:vc animated:YES];
First create any NSDictionary object or Your model class object on OtherViewController where you want to navigate then write code like Below,
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
OtherViewController *VC = [[OtherViewController alloc] init];
VC.objContactModel = [_Contacts objectAtIndex:indexPath.row];
[self.navigationController pushViewController:VC animated:YES];
}
Hope it will work.

Data Written to Plist is not saving

I made a few changes to the plist like inserting,deleting and reordering rows in a table.plist is changing to default on viewDidDisappear.
I tried the following code.
-(NSString *)dataFilePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataFile = [documentsDirectory stringByAppendingPathComponent:#"ETCategoryList.plist"];
return dataFile;
}
//Code for deleting.
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if(editingStyle == UITableViewCellEditingStyleDelete){
[[self categoriesArray]removeObjectAtIndex:[indexPath row]];
NSArray *indexPathsToRemove = [NSArray arrayWithObject:indexPath];
[tableView deleteRowsAtIndexPaths:indexPathsToRemove withRowAnimation:UITableViewRowAnimationLeft];
[tableView reloadData];
NSArray *revisedArray = [[NSArray alloc]initWithArray:self.categoriesArray];
[revisedArray writeToFile:[self dataFilePath] atomically:YES];
}
}
Your code is :
NSArray *revisedArray = [[NSArray alloc]initWithArray:self.categoriesArray];
[revisedArray writeToFile:[self dataFilePath] atomically:YES];
which is correct!!!
The problem should be from self.categoriesArray, if the array contains some objects/ custom object then you can not write directly.
You need to archive it to NSData
NSData *objData = [NSKeyedArchiver archivedDataWithRootObject:object];
Or you can endcode it in your Custom Class.
- (void) encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:obj1 forKey:#"key1"];
[encoder encodeFloat:obj2 forKey:#"key2"];
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:coder];
obj1 = [coder decodeObjectForKey:#"key1"];
obj2 = [coder decodeObjectForKey:#"key2"];
return self;
}
your code is fine enough. its working well with me.
Sample code:
self.clickMeArray = [[NSMutableArray alloc] init];
for(int i =1; i<10;i++)
{
[self.clickMeArray addObject:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:#"n%d",i] forKey:[NSString stringWithFormat:#"iN%d",i]]];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataFile = [documentsDirectory stringByAppendingPathComponent:#"MyName.plist"];
[self.clickMeArray writeToFile:dataFile atomically:YES];
try to clean Build and Relaunch.
Try this
- (void)viewDidLoad
{
[super viewDidLoad];
UIBarButtonItem *lefttBtn = [[UIBarButtonItem alloc] initWithTitle:#"Edit" style:UIBarButtonItemStylePlain
target:self action:#selector(EditTable:)];
[[self navigationItem] setLeftBarButtonItem:lefttBtn];
[lefttBtn release];
}
- (void) EditTable:(id)sender
{
if(self.editing)
{
[super setEditing:NO animated:NO];
[table setEditing:NO animated:NO];
[table reloadData];
[self.navigationItem.leftBarButtonItem setTitle:#"Edit"];
[self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStylePlain];
}
else
{
[super setEditing:YES animated:YES];
[table setEditing:YES animated:YES];
[table reloadData];
[self.navigationItem.leftBarButtonItem setTitle:#"Done"];
[self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStyleDone];
}
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if(editingStyle == UITableViewCellEditingStyleDelete){
[[self categoriesArray]removeObjectAtIndex:indexPath.row];
[[self categoriesArray] writeToFile:[self dataFilePath] atomically:YES];
[tableView reloadData];
}
}

Custom UITableViewCell re-creating itself

Really need help. I've looked everywhere but still i cant find an answer. So, when i scroll my UITableView with custom cells in it its recreating cell each time I see it. As the result it lowers my performance significantly.
my method
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = #"CellWithViewForProduct";
ProductCell *cell = (ProductCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
ProductDataStruct *dataStruct = [self.arrayData objectAtIndex:indexPath.row];
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"productCell" owner:nil options:nil];
for(id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[ProductCell class]])
{
cell = (ProductCell *)currentObject;
break;
}
}
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.roundingIncrement = [NSNumber numberWithDouble:0.01];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *price = [formatter stringFromNumber:[NSNumber numberWithFloat:(dataStruct.price.floatValue * [[[NSUserDefaults standardUserDefaults] objectForKey:#"CurrencyCoefficient"] floatValue])]];
NSString *priceString = [NSString stringWithFormat:#"%# %#", price, [[NSUserDefaults standardUserDefaults] objectForKey:#"Currency"]];
cell.productPrice.text = priceString;
cell.productDescription.text = [NSString stringWithFormat:#"%#", dataStruct.descriptionText];
cell.productTitle.text = [NSString stringWithFormat:#"%#", dataStruct.title];
if (dataStruct.hit.integerValue == 1)
{
[cell.productImage.layer addSublayer:[hitView layer]];
}
else
if (dataStruct.hit.integerValue == 2)
[cell.productImage.layer addSublayer:[newsItemView layer]];
if (!dataStruct.image)
{
if (self.tableView.dragging == NO && self.tableView.decelerating == NO && dataStruct.link)
{
[self startIconDownload:dataStruct forIndexPath:indexPath];
}
// if a download is deferred or in progress, return a placeholder image
//cell.productImage.image = [UIImage imageNamed:#"Placeholder.png"];
// if a download is deferred or in progress, return a loading screen
cell.productImage.alpha = 0;
[cell.productImageLoadingIndocator startAnimating];
}
else
{
if (self.didLoad)
{
cell.productImage.alpha = 0;
}
[cell.productImageLoadingIndocator stopAnimating];
cell.productImage.image = dataStruct.image;
[self imageAnimation: cell.productImage];
}
NSLog(#"WAZAAA");
return cell;
}
This entire chunk of code:
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"productCell" owner:nil options:nil];
for(id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[ProductCell class]])
{
cell = (ProductCell *)currentObject;
break;
}
}
seems wrong to me. Above it,
ProductCell *cell = (ProductCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
should be sufficient to get you a cell to use.
first create a #property (nonatomic, assign) IBOutlet ProductCell *prodCell; in the .h
Then in the .m you just need this
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = #"CellWithViewForProduct";
ProductCell *cell = (ProductCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"productCell" owner:self options:nil];
cell = prodCell;
self.prodCell = nil;
NSLog(#"WAZAAA"); //Now it will only be called when a new cell is created.
}
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.roundingIncrement = [NSNumber numberWithDouble:0.01];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *price = [formatter stringFromNumber:[NSNumber numberWithFloat:(dataStruct.price.floatValue * [[[NSUserDefaults standardUserDefaults] objectForKey:#"CurrencyCoefficient"] floatValue])]];
NSString *priceString = [NSString stringWithFormat:#"%# %#", price, [[NSUserDefaults standardUserDefaults] objectForKey:#"Currency"]];
cell.productPrice.text = priceString;
cell.productDescription.text = [NSString stringWithFormat:#"%#", dataStruct.descriptionText];
cell.productTitle.text = [NSString stringWithFormat:#"%#", dataStruct.title];
if (dataStruct.hit.integerValue == 1)
{
[cell.productImage.layer addSublayer:[hitView layer]];
}
else
if (dataStruct.hit.integerValue == 2)
[cell.productImage.layer addSublayer:[newsItemView layer]];
if (!dataStruct.image)
{
if (self.tableView.dragging == NO && self.tableView.decelerating == NO && dataStruct.link)
{
[self startIconDownload:dataStruct forIndexPath:indexPath];
}
// if a download is deferred or in progress, return a placeholder image
//cell.productImage.image = [UIImage imageNamed:#"Placeholder.png"];
// if a download is deferred or in progress, return a loading screen
cell.productImage.alpha = 0;
[cell.productImageLoadingIndocator startAnimating];
}
else
{
if (self.didLoad)
{
cell.productImage.alpha = 0;
}
[cell.productImageLoadingIndocator stopAnimating];
cell.productImage.image = dataStruct.image;
[self imageAnimation: cell.productImage];
}
NSLog(#"WAZAAA"); //Here doesn't make any sense, the cell is returned for being displayed, this doesn't mean it's being created.
return cell;
}

Remove Image From NSMutableArray

So, the app that I'm writing allows the user to upload a photo from their camera roll, and it displays in a UIImageView. I have a "Save" button, that allows the images to be saved when pressed. I also have an "Edit" button, when tapped, it allows the user to tap on the photo and it will be deleted. This is where I'm having issues, the image deletes from the view, but doesn't seem to delete from the array. When I close and relaunch the app, the photo appears again. I'm very new to Objective-C, I'm surprised that I even made it this far, so I'm having issues figuring out how to delete it from the array.
Also, as a side note, if I grab 3 images from the camera roll, delete the middle one, and then press the save button, after closing and relaunching the app it displays only the 2 photos like it should. The issue regarding the image appearing again after relaunch only happens if I press save first, then try and delete them.
This is how I'm deleting them. I have an invisible button over each UIImageView, and when the Edit button is pressed, it unhides them. I've tagged both the buttons and the UIImageViews, and when one of the buttons is pressed, this fires:
- (IBAction)deleteButtonPressed:(id)sender {
UIAlertView *deleteAlertView = [[UIAlertView alloc] initWithTitle:#"Delete"
message:#"Are you sure you want to delete this photo?"
delegate:self
cancelButtonTitle:#"No"
otherButtonTitles:#"Yes", nil];
[deleteAlertView show];
int imageIndex = ((UIButton *)sender).tag;
deleteAlertView.tag = imageIndex;
}
- (UIImageView *)viewForTag:(NSInteger)tag {
UIImageView *found = nil;
for (UIImageView *view in self.array) {
if (tag == view.tag) {
found = view;
break;
}
}
return found;
}
- (void)alertView: (UIAlertView *) alertView
clickedButtonAtIndex: (NSInteger) buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex]) {
UIImageView *view = [self viewForTag:alertView.tag];
if (view) {
[self.array removeObject:view];
}
((UIImageView *)[self.view viewWithTag:alertView.tag]).image =nil;
}
[self.user setObject:self.array forKey:#"images"];
}
And just for reference, this is how I'm saving the images:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {
if (imageView.image == nil) {
imageView.image = img;
[self.array addObject:imageView];
[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;
}
if (imageView2.image == nil) {
imageView2.image = img;
NSLog(#"The image is a %#", imageView);
[self.array addObject:imageView2];
[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;
}
...
...
}
-(IBAction)saveButtonPressed:(id)sender {
NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];
for (UIImageView *imageViewToSave in self.array) {
NSInteger tag = imageViewToSave.tag;
UIImage *image = imageViewToSave.image;
NSString *imageName = [NSString stringWithFormat:#"Image%i.png",tag];
NSString *imagePath = [docsDir stringByAppendingPathComponent:imageName];
[UIImagePNGRepresentation(image) writeToFile:imagePath atomically:NO];
}
}
And this is how I'm loading them:
-(void)viewDidLoad {
self.array = [NSMutableArray array];
NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSArray *docFiles = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:docsDir error:NULL];
for (NSString *fileName in docFiles) {
if ([fileName hasSuffix:#".png"]) {
NSString *fullPath = [docsDir stringByAppendingPathComponent:fileName];
UIImage *loadedImage = [UIImage imageWithContentsOfFile:fullPath];
if (!imageView.image) {
imageView.image = loadedImage;
}
else if (!imageView2.image) {
imageView2.image = loadedImage;
}
else if (!imageView3.image) {
imageView3.image = loadedImage;
}
}
}
}
Update: Here is my current code:
- (IBAction)deleteButtonPressed:(id)sender {
NSLog(#"Sender is %#", sender);
UIAlertView *deleteAlertView = [[UIAlertView alloc] initWithTitle:#"Delete"
message:#"Are you sure you want to delete this photo?"
delegate:self
cancelButtonTitle:#"No"
otherButtonTitles:#"Yes", nil];
[deleteAlertView show];
int imageIndex = ((UIButton *)sender).tag;
deleteAlertView.tag = imageIndex;
}
- (UIImageView *)viewForTag:(NSInteger)tag {
UIImageView *found = nil;
for (UIImageView *view in self.array) {
if (tag == view.tag) {
found = view;
break;
}
}
return found;
}
- (void)alertView: (UIAlertView *) alertView
clickedButtonAtIndex: (NSInteger) buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex]) {
UIImageView *view = [self viewForTag:alertView.tag];
if (view) {
[self.array removeObject:view];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"Image%i.png",view.tag]];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:filePath error:NULL];
}
((UIImageView *)[self.view viewWithTag:alertView.tag]).image =nil;
}
[self.user setObject:self.array forKey:#"images"];
}
When you're deleting the image from the array [self.array removeObject:view];, you haven't removed the image itself from the directory.
You may want to do something like this after removing the object from array:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"THE_IMAGE_NAME_HERE.png"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
[fileManager removeItemAtPath:filePath error:&error];
if (error)
NSLog(#"Error: %#",error);
Your array has nothing to do with this. It is overwritten on the next launch anyway. I don't think you are ever deleting your image from the folder, so it is read again on the next launch in your viewDidLoad method.

cannot delete the right cell in the table

I am making a small app. And having a trouble right now. Trouble by deleting a table customized cell.
it keep removing the top cell instead of the right selected cell. I delete cell number 20, it still delete the cell number 1. I don't know why. please help me out. Really appreciate.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[sortedArray removeObjectAtIndex:indexPath.row];
[self.tableView reloadData];
}
and here is the array:
- (void)viewDidLoad
{
[super viewDidLoad];
if (detail == nil) {
detail = [[UrlDetail alloc] init];
}
NSString *path = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"plist"];
self.arrayData = [NSMutableArray arrayWithContentsOfFile:path];
NSMutableArray *filterArr = [self filterArray];
sortedArray = [[NSMutableArray alloc] initWithArray:filterArr copyItems:YES];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:#selector(actionAddNewURL:)] autorelease];
}
and here is the filter function:
-(NSMutableArray *)filterArray
{
NSMutableArray *filterArr = [[NSMutableArray alloc] init];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[filterArr addObject:tempArray];
[tempArray release];
for (NSDictionary *item in arrayData) {
if ([tempArray count]==0)
{
[tempArray addObject:item];
}
else
{
NSDictionary *anItem = [tempArray objectAtIndex:0];
NSString *first = [[anItem objectForKey:#"url"] substringToIndex:1];
NSString *last = [[item objectForKey:#"url"] substringToIndex:1];
if ( [first isEqualToString:last])
{
[tempArray addObject:item];
} else
{
tempArray = [[NSMutableArray alloc] init];
[tempArray addObject:item];
[filterArr addObject:tempArray];
[tempArray release];
}
}
}
// NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:filterArr copyItems:YES];
return filterArr;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if([sortedArray count]>0){
NSLog(#"number of section: %d", [sortedArray count]);
return [sortedArray count];
}
return 0;
}
- (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:(NSInteger)section
{
if (isTab) {
if ([self.sortedArray count] > section) {
NSDictionary *dictionary = [[sortedArray objectAtIndex:section] objectAtIndex:0];
NSString *string = [dictionary objectForKey:#"url"];
return [NSString stringWithFormat:#"%#", [[string substringToIndex:1] uppercaseString]];
}
else return nil;
} else
{
return nil;
}
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = (CustomCell *)[aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
[[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
cell = myOwnCell;
}
NSDictionary *dataItem = [[sortedArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
cell.urlName.text = [dataItem objectForKey:#"url"];
cell.titleLabel.text = [dataItem objectForKey:#"title"];
cell.urlName.font = [UIFont italicSystemFontOfSize:14.0];
cell.imageIcon.image = [UIImage imageNamed:[dataItem objectForKey:#"image"]];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// Configure the cell.
return cell;
}
Try this one if it works:
- (void) tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSString *key = [[sortedArray allKeys] objectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
[sortedArray removeObjectForKey:key];
}
}