Objective-C, iOS SDK, NSMutableArray, add elements and save data - objective-c

Basically, every time I enter something in my textfield and save it to the table, the previous entry will be replaced by the new one. How do I add elements in a mutable array and save the last entry? I tried
[tabledata addObject....
and in the entry
tabledata.lastObject objectAtIndex...
but that didn't work.
here is what I have:
-(void)viewDidLoad
{
[super viewDidLoad];
titlestring = [[NSUserDefaults standardUserDefaults] objectForKey:#"titlehomework" ];
detailsstring = [[NSUserDefaults standardUserDefaults] objectForKey:#"detailshomework"];
tabledata = [[NSMutableArray alloc] initWithObjects:titlestring, nil];
tablesubtitles = [[NSMutableArray alloc] initWithObjects:detailsstring, nil];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
return [tabledata count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
UITableViewCell *cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:#"homeworkcell"];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"homeworkcell"];
}
cell.textLabel.text = [tabledata objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [tablesubtitles objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont systemFontOfSize:14.0];
cell.textLabel.backgroundColor = [ UIColor clearColor ];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
//-----------------------------------------START----------------------------Set image of cell----
cellImage = [UIImage imageNamed:#"checkboxblank.png"];
cell.imageView.image = cellImage;
//--------------------------------------------END---------------------------end set image of cell--
return cell;
}

Without seeing more code, the best I can do is suggest something like this
[tabledata addObject:newTitle];
[tablesubtitles addObject:newSubtitle];
[tableView reloadData];
This assumes both newTitle and newSubtitle are the NSStrings you wish to add and that tableView is the pointer to the UITableView.

Related

Why my tableView did not display anything

i want select over 50 in the first section,and others in the second section ,but there is no value display in tableView ,and when i use NSlog("%#",self.over50) ,there is no reaction
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell" ];
NSArray* items = [[BNRItemStore shareStore] allItems];
self.itemsUnder50 = [[NSMutableArray alloc] init];
self.itemsOver50 = [[NSMutableArray alloc] init];
for (BNRItem *item in items) {
if (indexPath.section ==0) {
[self.itemsOver50 addObject:item];
cell.textLabel.text = [self.itemsOver50[indexPath.row] description];
NSLog(#"%#",self.itemsUnder50);
}
else if(indexPath.section == 1){
[self.itemsUnder50 addObject:item];
cell.textLabel.text = [self.itemsUnder50[indexPath.row] description];
}
}
return cell;
}
connect the datasource and delegate of the tableview to the viewController

Selected row changes when scrolling UITableView

currently my situation is my fist row is checked by default. but when i want to uncheck it, it need user to click twice to uncheck it. may i know where i done wrongly?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = #"Report_SelectGroupTableViewCell";
Report_SelectGroupTableViewCell *cell = (Report_SelectGroupTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil){
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"Report_SelectGroupTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.indexPath = indexPath;
cell.delegate = self;
}
// [myTableView selectRowAtIndexPath:0 animated:NO scrollPosition:UITableViewScrollPositionNone];
//[self tableView:myTableView didSelectRowAtIndexPath:0];
[cell setSelectionStyle:NO];
NSString *groupID = [[groupArray objectAtIndex:indexPath.row] objectForKey:#"group_id"];
if ([groupID isEqualToString:selectedGroup]){
NSMutableDictionary *dict = [groupArray objectAtIndex:indexPath.row];
BOOL isSelected = [[dict objectForKey:#"isSelected"] boolValue];
if (!isSelected) {
isSelected = !isSelected;
[dict setObject:[NSNumber numberWithBool:isSelected] forKey:#"isSelected"];
}
cell.userInteractionEnabled = NO;
}
cell.groupName.text = [[groupArray objectAtIndex:indexPath.row] objectForKey:#"group_name"];
NSMutableDictionary *typeDict = [groupArray objectAtIndex:indexPath.row];
cell.tickButton.selected = [[typeDict objectForKey:#"isSelected"] boolValue];
if (cell.tickButton.selected) {
[cell.tickButton.layer setBorderColor:[UIColor clearColor].CGColor];
if([cell.groupName.text isEqual:#"All Users"])
{
[cell.tickButton setImage:[UIImage imageNamed:#"tick_Icon_empty.png"] forState:UIControlStateNormal];
}
}
else{
[cell.tickButton.layer setBorderColor:[UIColor whiteColor].CGColor];
}
if([cell.groupName.text isEqual:#"All Users"])
{
[cell.tickButton setImage:[UIImage imageNamed:#"tick_Icon.png"] forState:UIControlStateNormal];
[cell.tickButton.layer setBorderColor:[UIColor clearColor].CGColor];
[typeDict setObject:#"1" forKey:#"isSelected"];
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
Report_SelectGroupTableViewCell *cell = (Report_SelectGroupTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
NSMutableDictionary *dict = [groupArray objectAtIndex:indexPath.row];
BOOL isSelected = [[dict objectForKey:#"isSelected"] boolValue];
isSelected = !isSelected;
[dict setObject:[NSNumber numberWithBool:isSelected] forKey:#"isSelected"];
if (cell.tickButton.isSelected == YES)
{
[cell.tickButton setSelected:NO];
[cell.tickButton.layer setBorderColor:[UIColor whiteColor].CGColor];
if([cell.groupName.text isEqual:#"All Users"])
{
[cell.tickButton setImage:[UIImage imageNamed:#"tick_Icon_empty.png"] forState:UIControlStateNormal];
}
}
else if (cell.tickButton.isSelected == NO)
{
[cell.tickButton setSelected:YES];
[cell.tickButton.layer setBorderColor:[UIColor clearColor].CGColor];
}
}
You should remove
[myTableView selectRowAtIndexPath:0 animated:YES scrollPosition:
UITableViewScrollPositionNone];
and use this to select the first row (this should be called once outside this method or you want to set this row selected everytime each cell is render)
[myTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
And I don't know why you called this in this method
[myTableView.delegate tableView:myTableView didSelectRowAtIndexPath:0];
but if you want to call it you should change to this too
[myTableView.delegate tableView:myTableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
ps. You should set the cell's selectionStyle correctly to see the cell is selected.
Update::
Try to replace all codes in the method with this
Report_SelectGroupTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Report_SelectGroupTableViewCell"];
if (!cell){
cell = [[[NSBundle mainBundle] loadNibNamed:#"Report_SelectGroupTableViewCell" owner:self options:nil] objectAtIndex:0];
}
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
[tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
return cell;
Please tell me if the first row is not selected and highlighted.

IOS custom cell with labels showing wrong text when cell reused

I have been trying to figure this out for a bit. I create a custom cell in its own xib file. In my view controller I have setup a table view controller with sections. The data that is being pulled into the table View is based off a fetch request controller from some core data that I have. I set up the custom cell in the cellForRowAtIndexPath function. I am creating a label for each cell within this function and populating the label with some data from the managed object. Everything seems ok when I first run. However, when I try to scroll up and down and new cells are reused the data in the labels are placed in the wrong cells. I have seen and heard this has to do with the reuse of cells. However, have not seen much examples on correcting this issue. Below is some of the code I have in my cellForRowAtIndexPath function. Let me know if any other input may be needed. Thanks for any help.
-(UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:#"CustomCell"];
/* do this to get unique value per cell due to sections. */
NSInteger indexForCell = indexPath.section * 1000 + indexPath.row + 1;
NSManagedObject *managedObject = [fetchedResultsController objectAtIndexPath:indexPath];
NSString *lastSession = nil;
UILabel *lastSessionLabel = nil;
if(cell == nil) {
lastSession = [managedObject valueForKey:#"last_session"];
[self.tableView registerNib:[UINib nibWithNibName:#"CustomCell"
bundle:[NSBundle mainBundle]]
forCellReuseIdentifier:#"CustomCell"];
self.tableView.backgroundColor = [UIColor clearColor];
cell = [aTableView dequeueReusableCellWithIdentifier:#"CustomCell"];
lastSessionLabel = [[UILabel alloc]initWithFrame:CGRectMake(410,55, 89, 35)];
lastSessionLabel.textAlignment = UITextAlignmentLeft;
lastSessionLabel.tag = indexForCell;
lastSessionLabel.font = [UIFont systemFontOfSize:17];
lastSessionLabel.highlighted = NO;
lastSessionLabel.backgroundColor = [UIColor clearColor];
cell.contentView.tag = indexForCell;
[cell.contentView addSubview:lastSessionLabel];
} else {
lastSessionLabel = (UILabel *)[cell viewWithTag:indexForCell];
}
if (lastSession && lastSession.length) {
lastSessionLabel.text = lastSession;
}
cell.textLabel.text = [NSString stringWithFormat:#"%#%#%#%#", #"Dr. ",
[managedObject valueForKey:#"first_name"],
#" " ,
[managedObject valueForKey:#"last_name"]];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.editingAccessoryType = UITableViewCellAccessoryNone;
return cell;
}
** Revised Code **
Below are the changes to code: in viewDidLoad is the following:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView registerNib:[UINib nibWithNibName:#"CustomCell"
bundle:[NSBundle mainBundle]]
forCellReuseIdentifier:#"CustomCell"];
self.tableView.backgroundColor = [UIColor clearColor];
}
in -(UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:#"CustomCell"];
NSInteger indexForCell = indexPath.section * 1000 + indexPath.row + 1;
NSLog(#"index for cell: %d",indexForCell);
NSManagedObject *managedObject = [fetchedResultsController objectAtIndexPath:indexPath];
NSString *lastSession = [managedObject valueForKey:#"last_session"];
UILabel *lastSessionLabel = nil;
if(cell == nil) {
NSLog(#"Cell is nil! %#", [managedObject valueForKey:#"first_name"]);
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CustomCell"];
self.tableView.backgroundColor = [UIColor clearColor];
}
lastSessionLabel = [[UILabel alloc]initWithFrame:CGRectMake(410,55, 89, 35)];
lastSessionLabel.textAlignment = UITextAlignmentLeft;
lastSessionLabel.tag = indexForCell;
lastSessionLabel.font = [UIFont systemFontOfSize:17];
lastSessionLabel.highlighted = NO;
lastSessionLabel.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:lastSessionLabel];
/* Appropriate verbiage for nil last session. */
if (lastSession && lastSession.length) {
lastSessionLabel.text = lastSession;
}
return cell;
}
I am still having issues again with the label cell text changing when I scroll for different cells. I read some where about maybe having to use the prepareForReuse function for this.
You are only fetching lastSession when you create a new cell. Try putting this line before the if(cell == nil) statement.
lastSession = [managedObject valueForKey:#"last_session"];
I.e. this:
NSString *lastSession = [managedObject valueForKey:#"last_session"];
in stead of this:
NSString *lastSession = nil;
UPDATE
You are also setting the same tag for two views:
lastSessionLabel.tag = indexForCell;
...
cell.contentView.tag = indexForCell;
Based on your code sample you should only use the first line, i.e. set the tag for the lastSessionLabel
SECOND UPDATE
You should also only call registerNib: once in your view lifecycle, e.g. in viewDidLoad, not every time you need a new cell. Furthermore, you should create a new cell if cell == nil in stead of using dequeueReusableCellWithIdentifier:. E.g.
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CustomCell"];

Pushing data from one View to another

I have a table list of promotions held in an NSSet which I load into an array for the purpose of displaying the title/name on the cell. However I want to use the didselectrow method to push the selected promotion onto an individual promotion page. I've making promo.featuredArray = self.featuredArray however it doesn't seem to be passing the data. My code is as follows.
Promo list.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
Featured*featured = [self.featuredArray objectAtIndex:indexPath.row];
cell.textLabel.text = featured.details;
cell.textLabel.textColor = [UIColor whiteColor];
cell.detailTextLabel.text = self.place.name;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
Promo * promo= [[Promo alloc] initWithNibName:#"Promo" bundle:nil];
//Featured*featured = [self.featuredArray objectAtIndex:indexPath.row];
promo.featuredArray = self.featuredArray;
[self.navigationController pushViewController:promo animated:YES];
[promo release];
//[featured release];
}
Promo.m
#synthesize featuredArray, featured = __featured;
- (void)viewDidLoad
{
self.clearImage = [UIImage imageNamed:#"fav_icon.png"];
self.clearImagePressed = [UIImage imageNamed:#"fav_icon_sel.png"];
Featured*featured = [self.featuredArray init];
self.name.text = [NSString stringWithFormat:#"%#", __featured.name];
self.time.text = [NSString stringWithFormat:#"%#", __featured.time];
// self.description.text = [NSString stringWithFormat:#"%#", __featured.description];
self.placeName.text = [NSString stringWithFormat:#"%#", __featured.Place];
[super viewDidLoad];
if([__featured.imageURL hasPrefix:#"http"])
{
[self getImageForPlace];
}
// else
// {
// [self refreshImage];
// }
//
self.title = #"Promotion";
UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"background_texture.png"]];
self.view.backgroundColor = background;
[background release];
[featured release];
}
It's probably this line:
Featured*featured = [self.featuredArray init];
This is wrong in many ways.
Making this a community wiki because I don't have time to write a full answer.

Can't Get Data Loaded on First Row of UITableView

I'm trying to parse an HTML Data using HTMLParser (by Ben Reeves) and display results on UITableView. For some reasons I'm able to show up results only on last row of the tableView. Here's the code snippet:
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSData *responseData = [request responseData];
NSError *error = [request error];
HTMLParser *parser = [[HTMLParser alloc] initWithData:responseData error:&error];
HTMLNode *bodyNode = [parser body];
arrayNodes = [bodyNode findChildrenWithAttribute:#"class" matchingName:#"foo" allowPartial:NO];
for (HTMLNode *arrayNode in arrayNodes) {
NSString *footitle = [arrayNode allContents];
NSLog(#"%#", footitle);
fooLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 200, 30)];
fooLabel.text = (#"%#", footitle);
fooLabel.textColor = [UIColor blackColor];
}
[self.fooTableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [arrayNodes count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}
// Configure the cell.
// [self.arrayNodes objectAtIndex:indexPath.row];
[cell.contentView addSubview:fooLabel];
return cell;
}
Where am I making the mistake?
for (HTMLNode *arrayNode in arrayNodes) {
NSString *footitle = [arrayNode allContents];
NSLog(#"%#", footitle);
fooLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 200, 30)];
fooLabel.text = (#"%#", footitle);
fooLabel.textColor = [UIColor blackColor];
}
You are creating fooLabel's with same Frame size and location as many as arrayNodes array.
then in [cell.contentView addSubview:fooLabel]; it is showing you the last value that label is updated with.
take out that fooLabel from for loop.
in your cellForRowAtIndexPath:
HTMLNode* arrayNode = [arrayNodes objectAtIndex:[indexPath row]];
cell.textLabel.text = [NSString stringWithFormat:#"%#",[arrayNode allContents]];
You need to create the foolabel in your cellForRowAtindexPath method. Right now only one foolabel is created, and it is applied to each cell in turn and then set to the next cell, leaving it placed on the last cell. So instead you should do this:
-
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}
// Configure the cell.
HTMLNode *arrayNode = [arrayNodes objectAtIndex:indexPath.row];
NSString *footitle = [arrayNode allContents];
UILabel *fooLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 200, 30)];
fooLabel.text = (#"%#", footitle);
fooLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview:fooLabel];
[fooLabel release];
return cell;
}