cannot delete the right cell in the table - objective-c

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];
}
}

Related

How to show UISearchbar bar only in tableview not on UINavigationbar in objective c

I am new in ios and I am facing problem regarding to UISearchbar. I have done code like this
.h
IBOutlet UITableView *table;
NSArray *recipes;
NSArray *searchResults;
.m
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
recipes = [NSArray arrayWithObjects:#"Egg Benedict", #"Mushroom Risotto", #"Full Breakfast", #"Hamburger", #"Ham and Egg Sandwich", #"Creme Brelee", #"White Chocolate Donut", #"Starbucks Coffee", #"Vegetable Curry", #"Instant Noodle with Egg", #"Noodle with BBQ Pork", #"Japanese Noodle with Pork", #"Green Tea", #"Thai Shrimp Cake", #"Angry Birds Cake", #"Ham and Cheese Panini", nil];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchResults count];
} else {
return [recipes count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
}
return cell;
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"SELF contains[cd] %#",
searchText];
searchResults = [recipes filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
But it shows me search bar on navigation bar
But I need to show it on the UItableView itself. Like this in Image
Thanks in advance
I have use code to search from 4 mutable array...
- (void)viewDidLoad {
[super viewDidLoad];
[searchtxt addTarget:self action:#selector(textFieldDidChangeClose:) forControlEvents:UIControlEventEditingChanged];
searchtxt.delegate=self;
}
#pragma mark - Seach Button...
-(void)textFieldDidChangeClose:(UITextField *)textField
{
searchTextString=textField.text;
[self updateSearchArray:searchTextString];
}
-(void)updateSearchArray:(NSString *)searchText
{
if(searchText.length==0)
{
isFilter=NO;
[table reloadData];
}
else{
isFilter=YES;
searchArray=[[NSMutableArray alloc]init];
searchArrayId=[[NSMutableArray alloc] init];
searchArraystatus=[[NSMutableArray alloc] init];
searchArraydescription=[[NSMutableArray alloc] init];
for(NSString *string in idarray){
NSRange stringRange=[string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location !=NSNotFound){
[searchArray addObject:string];
NSInteger index = [idarray indexOfObject:string];
[searchArraystatus addObject:[shortnamearray objectAtIndex:index]];
[searchArraydescription addObject:[descarray objectAtIndex:index]];
[searchArrayId addObject:[complaintidArray objectAtIndex:index]];
}
}
[table reloadData];
}
}
#pragma mark - TableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(isFilter)
{
return [searchArray count];
}
else
{
return [idarray count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *STI=#"STI";
IBTClosedComplaintCell *cell = (IBTClosedComplaintCell *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:STI];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"IBTClosedComplaintCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.accessoryType=UITableViewCellAccessoryNone;
}
if(isFilter)
{
cell.Complaintnamelbl.text=[NSString stringWithFormat:#"%#",[searchArray objectAtIndex:indexPath.row]];
cell.statuslbl.text = [NSString stringWithFormat:#"%#",[searchArraystatus objectAtIndex:indexPath.row]];
cell.descriptiolbl.text=[NSString stringWithFormat:#"%#",[searchArraydescription objectAtIndex:indexPath.row]];
cell.complaintidlbl.text = [NSString stringWithFormat:#"%#",[searchArrayId objectAtIndex:indexPath.row]];
}
else
{
cell.Complaintnamelbl.text=[idarray objectAtIndex:indexPath.row];
cell.statuslbl.text=[shortnamearray objectAtIndex:indexPath.row];
cell.descriptiolbl.text=[descarray objectAtIndex:indexPath.row];
cell.complaintidlbl.text=[NSString stringWithFormat:#"%#",[complaintidArray objectAtIndex:indexPath.row]];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
IBTClosedNextScreen *next =[[IBTClosedNextScreen alloc] initWithNibName:#"IBTClosedNextScreen" bundle:nil];
[self.navigationController pushViewController:next animated:YES];
if(isFilter)
{
str1=[NSString stringWithFormat:#"%#",[searchArrayId objectAtIndex:indexPath.row]];
NSLog(#"String =%#",str1);
next.str =str1;
}
else
{
str1=[NSString stringWithFormat:#"%#",[self.complaintidArray objectAtIndex:indexPath.row]];
NSLog(#"String =%#",str1);
next.str =str1;
}
}

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.

Uncheck (unfavorite) items in Favorites Table View

I have a tableview that displays a list of "favorited" items. Users favorite items in another tableview, and favorited items are listed in this tableview (FavoritesTableView.m).
For some reason, I can't get checked items (favorited items) to "uncheck" from the FavoritesTableView? What am I missing?
See the .m file below...
FavoritesViewController.h
#import <UIKit/UIKit.h>
#import "StrainTableCell.h"
#interface FavoritesViewController : UITableViewController
{
}
#property (strong, nonatomic) NSArray *favoritesArrayset;
#property (strong, nonatomic) IBOutlet UITableView *favoritesTable;
#property (nonatomic, strong) NSMutableArray * favoritesArray;
- (IBAction)backbuttonpressed: (UIBarButtonItem *)sender;
#end
FavoritesViewController.m
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
if (favoritesArray == Nil)
{
favoritesArray = [[NSMutableArray alloc] init];
}
else
{
[favoritesArray removeAllObjects];
}
NSData *dataSave = [[NSUserDefaults standardUserDefaults] objectForKey:#"strains"];
if (dataSave != Nil)
{
favoritesArrayset = [NSKeyedUnarchiver unarchiveObjectWithData:dataSave];
for (NSDictionary *item in favoritesArrayset)
{
BOOL isChecked = [[item objectForKey:#"checked"] boolValue];
if (isChecked == YES )
{
[favoritesArray addObject:item];
}
}
}
[favoritesTable reloadData];
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return favoritesArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *Strains = [favoritesArray copy];
NSArray *dataArray = [favoritesArray copy];
static NSString *strainTableIdentifier = #"StrainTableCell";
StrainTableCell *cell = (StrainTableCell *)[tableView dequeueReusableCellWithIdentifier:strainTableIdentifier];
if (cell == nil)
{
cell = [[StrainTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strainTableIdentifier] ;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"StrainTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.titleLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Title"];
cell.descriptionLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Description"];
cell.ratingLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Rating"];
cell.ailmentLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Ailment"];
cell.actionLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Action"];
cell.ingestLabel.text = [[Strains objectAtIndex:indexPath.row] objectForKey:#"Ingestion"];
cell.whatCellamI = [NSNumber numberWithInt:indexPath.row];
NSMutableDictionary *item = [dataArray objectAtIndex:indexPath.row];
cell.textLabel.text = [item objectForKey:#"text"];
[item setObject:cell forKey:#"StrainTableCell"];
}
BOOL checked = [[item objectForKey:#"checked"] boolValue];
UIImage *image = (checked) ? [UIImage imageNamed:#"checked.png"] : [UIImage imageNamed:#"unchecked.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.frame = frame;
[button setBackgroundImage:image forState:UIControlStateNormal];
[button addTarget:self action:#selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
StrainDetailViewController *detailViewController = [[StrainDetailViewController alloc]
initWithNibName:#"StrainDetailViewController" bundle:nil];
detailViewController.title = [[favoritesArray objectAtIndex:indexPath.row] objectForKey:#"Title"];
detailViewController.strainDetail = [favoritesArray objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailViewController animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 82;
}
- (IBAction)backbuttonpressed:(id)sender
{
[self.view.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
}
- (void)checkButtonTapped:(id)sender event:(id)event
{
NSLog(#"made it here and event is %#",event);
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.favoritesTable];
NSIndexPath * indexPath ;
indexPath = [self.favoritesTable indexPathForRowAtPoint: currentTouchPosition];
NSLog(#"indexpath is below");
NSLog(#"%#",indexPath);
if (indexPath != Nil)
{
NSMutableDictionary *item = [favoritesArray objectAtIndex:indexPath.row];
BOOL isItChecked = [[item objectForKey:#"checked"] boolValue];
/*
if (isItChecked == NO) {
NSMutableArray *tmpArray = [[NSMutableArray alloc] init];
NSMutableArray *tmpArray2 = [[NSMutableArray alloc] initWithArray:[favoritesArray allObjects]];
NSString *text1 = [item objectForKey:#"Title"];
for (NSDictionary * object in tmpArray2) {
NSString *text2 = [object objectForKey:#"Title"];
if (![text1 isEqualToString:text2]) {
[tmpArray addObject:object];
}
}
// [favoritesArray removeAllObjects];
favoritesArray = [tmpArray copy];
}
*/
NSMutableArray *quickArray = [[NSMutableArray alloc] initWithArray:favoritesArray];
[quickArray replaceObjectAtIndex:indexPath.row withObject:item];
[item setObject:[NSNumber numberWithBool:!isItChecked] forKey:#"checked"];
favoritesArray = [quickArray copy];
// [self.favoritesArray addObject:item];
// NSLog(#"you have added %d items to favorites", self.favoritesArray.count);
[favoritesTable reloadData];
}
#end
In your .h take one NSMutableDictionary and do property to it.
In your .m synthesize it,and in viewdidLoad alloc the Dictionary.
Now put this below code in CellForRowAtIndex
if([idDictonary objectForKey:[NSString stringWithFormat:#"%d",[indexPath row]]])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
and put this below code in DidSelectRowAtIndex
UITableViewCell *thisCell = [tableView cellForRowAtIndexPath:indexPath];
if (thisCell.accessoryType == UITableViewCellAccessoryNone)
{
thisCell.accessoryType = UITableViewCellAccessoryCheckmark;
[idDictonary setValue:[dataArray objectAtIndex:indexPath.row] forKey:[NSString stringWithFormat:#"%d",[indexPath row]]];
}
else
{
if([idDictonary objectForKey:[NSString stringWithFormat:#"%d",[indexPath row]]])
{
[idDictonary removeObjectForKey:[NSString stringWithFormat:#"%d",[indexPath row]]];
thisCell.accessoryType = UITableViewCellAccessoryNone;
}
}
[myTableView reloadData];
NSLog(#"idDictonary = %#",idDictonary);
i hope this will helps u Brittany...
Every time -tableView:cellForRowAtIndexPath: runs, you create a new button, set it to the desired properties and … throw it away. (Seems to be the running joke this week.) You have to use the existing button.

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;
}

NSMutableDictionary and NSArray

I am splitting a String:
#"Sam|26|Developer,Hannah|22|Team Leader,Max|1|Dog"
and using NSMutableDictionary to display in a TableViewCell with 3 labels. Code:
- (void)viewDidLoad {
[super viewDidLoad];
NSString *test = #"Sam Parrish|26|Developer,Hannah Rajamets|22|Team Leader,Max Parrish|1|Dog";
testArray = [[NSArray alloc] init];
testArray = [test componentsSeparatedByString:#","];
dict = [NSMutableDictionary dictionary];
for (NSString *s in testArray) {
testArrayNew = [s componentsSeparatedByString:#"|"];
[dict setObject:[testArrayNew objectAtIndex:1] forKey:[testArrayNew objectAtIndex:0]];
[dict setObject:[testArrayNew objectAtIndex:2] forKey:[testArrayNew objectAtIndex:1]];
NSLog(#"Dictionary: %#", [dict description]);
}
[dict retain];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[dict allKeys] count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CustomCell";
untitled *cell = (untitled *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"untitled" owner:nil options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (untitled *) currentObject;
break;
}
}
}
// Configure the cell.
cell.nameLabel.text = [[dict allKeys] objectAtIndex:[indexPath row]];
cell.ageLabel.text = [dict objectForKey:cell.nameLabel.text];
cell.jobLabel.text = [dict objectForKey:cell.ageLabel.text];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
this is displaying 6 TableViewCells when I run, 3 of which are perfect, the other 3 are an assortment of the data. i realise this is to do with the setObject: forKey: but can't seem to find the solution for this to work correctly.
any help much appreciated..
sam
I would store the data as an NSArray holding NSArrays....
- (void)viewDidLoad {
[super viewDidLoad];
NSString *test = #"Sam Parrish|26|Developer,Hannah Rajamets|22|Team Leader,Max Parrish|1|Dog";
data = [[NSMutableArray alloc] init];
for (NSString *s in testArray) {
[data addObject:[s componentsSeparatedByString:#"|"]];
}
}
Then in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
use
// Configure the cell.
NSArray *cellData = [data objectAtIndex:indexPath.row];
cell.nameLabel.text = [cellData objectAtIndex:0];
cell.ageLabel.text = [cellData objectAtIndex:1];
cell.jobLabel.text = [cellData objectAtIndex:2];
If I understand you correctly, you're saying that the first three cells are correct and the other three shouldn't be shown at all? If that's the case, the problem is this:
return [[dict allKeys] count];
Shouldn't it be...
return [testArray count];
...in which case, you need to retain testArray.
In addition, you have a memory leak. You create an instance of NSArray, then you immediately leak it by assigning the return value of componentsSeparatedByString: to the same variable. Have you run the static analyser over your code?