iOS : reloadData not working - ios

I'm new to the whole iOS developement, so not really good at it. I currently have a viewController with two tableviews. The first table is always visible and contains categories. The second table should only be visible when a cell from the first table is selected. The second table then contains subitems from the cell that was selected in the first tableview. Both tableviews are connected to their property in the .h file.
The viewcontroller itself is connected to a FoodAddViewController.h and FoodAddViewController.m file.
In the FoodAddViewController.h file, I have:
#import <UIKit/UIKit.h>
#class FoodAddViewController;
#interface FoodAddViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>
#property (strong, nonatomic) IBOutlet UITableView *Categorien;
#property (strong, nonatomic) IBOutlet UITableView *Invulling;
- (IBAction)cancel:(id)sender;
#end
For the FoodAddViewController.m, I have:
#interface FoodAddViewController ()
{
NSArray *CategoryLabel;
NSMutableArray *elementen;
}
#end
#implementation FoodAddViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.Categorien.layer.transform = CATransform3DRotate(CATransform3DIdentity,-1.57079633,0,0,1);
self.Categorien.frame=CGRectMake(0,200, 700,234);
[self.Invulling setHidden:TRUE];
self.Invulling.layer.transform = CATransform3DRotate(CATransform3DIdentity,-1.57079633,0,0,1);
self.Invulling.frame=CGRectMake(0,200, 700,234);
self.Categorien.dataSource = self;
self.Categorien.delegate = self;
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"categorie" ofType:#"txt"];
NSString *content = [NSString stringWithContentsOfFile:filePath
encoding:NSMacOSRomanStringEncoding
error:NULL];
NSArray * categories = [content componentsSeparatedByString:#"\n"];
CategoryLabel = categories;
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(self.Categorien==tableView) {
return CategoryLabel.count;
}
if(self.Invulling==tableView) {
return elementen.count;
}
return 0;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(self.Categorien==tableView) {
static NSString *CellIdentifier = #"Cell";
CustomCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!Cell) {
Cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.layer.transform = CATransform3DRotate(CATransform3DIdentity,1.57079633,0,0,1);
Cell.frame=CGRectMake(0,0,234,150);
Cell.textLabel.text = [CategoryLabel objectAtIndex:indexPath.row];
return Cell;
}
if(self.Invulling==tableView) {
static NSString *CellIdentifier = #"DetailCell";
CustomCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!Cell) {
Cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.layer.transform = CATransform3DRotate(CATransform3DIdentity,1.57079633,0,0,1);
Cell.frame=CGRectMake(0,0,234,150);
Cell.textLabel.text = [elementen objectAtIndex:indexPath.row];
return Cell;
}
return NULL;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 200;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.Invulling.dataSource = self;
self.Invulling.delegate = self;
elementen = [[NSMutableArray alloc]init];
if(self.Categorien==tableView) {
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
PFQuery *query = [PFQuery queryWithClassName:cellText];
[query selectKeys:#[#"Naam"]];
NSArray *result = [query findObjects];
for (PFObject *object in result) {
NSString *naam = object[#"Naam"];
if(![elementen containsObject:naam]) {
[elementen addObject:naam];
}
}
}
[self.Invulling setHidden:FALSE];
[self.Invulling reloadData];
}
end
Now, the problem is that the reloadData method does not work correctly. For example: if I press the first cell from the first tableview (Categorien), then nothing happens. But when I click another cell, the second tableview (Invulling) gets loaded with the results from the first cell.

you have to use didSelectRowAtIndexPath not didDeselectRowAtIndexPath method
Also look up some tutorial on debugging, you could have known that the method is not
being called if you have added breakpoints

You are using
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:
Instead, use
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:

Related

how to get the selected cell values and unselected cell values in uitableview in different array using objective c

pls check the image
i am very new to iOS how to get the selected cell values in one array and unselected cell value in the another array using by using checkmarks in objective c
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *selectedRows=[_mytableview indexPathsForSelectedRows];
indexofselectedcell = [[NSMutableArray alloc]init];
valueofselectedcell = [[NSMutableArray alloc]init];
for (int i=0; i<selectedRows.count; i++) {
[indexofselectedcell addObject:indexPath
customcell *cell = (customcell *)[_mytableview cellForRowAtIndexPath:indexPath];
NSString *test = cell.balance.text;
[valueofselectedcell addObject:test];
NSLog(#"%# the value of the selected cell value is ",valueofselectedcell);
NSArray *array = [valueofselectedcell copy];
NSNumber* sum = [array valueForKeyPath: #"#sum.self"];
NSLog(#"the sum valuie is .... %#",sum);
NSString *totalamount = [sum stringValue];
_amountlabel.text=totalamount;
NSInteger index = [valueofselectedcell indexOfObject:totalamount];
NSLog(#"%ld the index value in the array is",(long)index);
}}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *totalamount;
if ([indexofselectedcell containsObject: indexPath])
{
NSInteger anIndex=[indexofselectedcell indexOfObject:indexPath];
[indexofselectedcell removeObjectAtIndex:anIndex];
[valueofselectedcell removeObjectAtIndex:anIndex];
NSLog(#"the value of the unselected cell value is..... %#",valueofselectedcell);
NSArray *array = [valueofselectedcell copy];
NSNumber* sum = [array valueForKeyPath: #"#sum.self"];
totalamount = [sum stringValue];
_amountlabel.text=totalamount;
totalamount= nil;
} }
Pavithra I tried sample project for your question and output.If I get unselected and selected cells in separate array,it crashed as I could not check two array in cellForRowAtIndexPath.So that I save selected and unSelected values in one array.
I created simple understandable solution.I have set values in tableview as unselected as default.If you selected(when you click the cell) it shows UITableViewCellAccessoryCheckmark and other show UITableViewCellAccessoryNone.
It works perfectly.You can easily get.
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
#property (strong, nonatomic) IBOutlet UITableView *tableViewSelectUnSelect;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController (){
NSMutableArray *arrVal,*arrSelectedUnSelectedValues,*arrSelectedValues,*arrUnSelectedValues;
NSMutableArray *arrSubTitle;
}
#end
#implementation ViewController
#synthesize tableViewSelectUnSelect;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrVal= [[NSMutableArray alloc]initWithObjects:#"India",#"China",#"Korea",#"Japan",#"Peru",#"Italy",#"France",#"US",#"Dubai",#"UK",#"Nepal",nil];
arrSubTitle = [[NSMutableArray alloc]initWithObjects:#"100",#"70",#"80",#"90",#"50",#"60",#"70",#"50",#"40",#"30",#"80",nil];
arrSelectedUnSelectedValues= [[NSMutableArray alloc]init];
arrSelectedValues = [[NSMutableArray alloc]init];
arrUnSelectedValues = [[NSMutableArray alloc]init];
for(int j=0;j<[arrVal count];j++)
{
[arrSelectedUnSelectedValues addObject:#"unselected"]; //As Default it is in UnSelected State
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UITableViewDataSource Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrVal.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *strCell = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
if(cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:strCell];
}
if([[arrSelectedUnSelectedValues objectAtIndex:indexPath.row] isEqualToString:#"selected"])
cell.accessoryType = UITableViewCellAccessoryCheckmark;
else
cell.accessoryType = UITableViewCellAccessoryNone;
cell.textLabel.text = [arrVal objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [arrSubTitle objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - UITableViewDelegate Methods
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
#try
{
CGPoint touchPoint = [cell convertPoint:CGPointZero toView:tableViewSelectUnSelect];
NSIndexPath *indexPath = [tableViewSelectUnSelect indexPathForRowAtPoint:touchPoint];
NSLog(#"The arrSelectedUnSelectedValues are %#",arrSelectedUnSelectedValues );
NSString *strValue;
if([arrSelectedUnSelectedValues count]==0)
{
for(int i=0; i<[arrVal count]; i++)
{
[arrSelectedUnSelectedValues addObject:#"unselected"];
}
}
if([[arrSelectedUnSelectedValues objectAtIndex:indexPath.row] isEqualToString:#"selected"])
{
cell.accessoryType = UITableViewCellAccessoryNone;
[arrSelectedUnSelectedValues replaceObjectAtIndex:indexPath.row withObject:#"unselected"];
strValue = cell.detailTextLabel.text;
[arrUnSelectedValues addObject:strValue];
NSLog(#"The arrUnSelectedValues are - %#",arrUnSelectedValues);
}
else
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[arrSelectedUnSelectedValues replaceObjectAtIndex:indexPath.row withObject:#"selected"];
strValue = cell.detailTextLabel.text;
[arrSelectedValues addObject:strValue];
NSLog(#"The arrSelectedValues - %#",arrSelectedValues);
}
}
#catch (NSException *exception) {
NSLog(#"The exception is-%#",exception);
}
}
#end
First when I run the application it shows like below
Then when I select values from the tableView
Then finally printed results are

iOS: How to display parameters in response in tableview?

I am trying to set up a UITableView inside of a UIViewController. I am using storyboard. but when running it on the simulator, the tableview does not display any content. Here is what i tried in Xcode:
1) Drag a table view on UIView.
2) Connect it's outlets (dataSource and delegate).
3) I get response from server like:
[{"email_id":"adas#faga.gs","id":66,"mobile_no":"1236547895","name":"asad","relation":"dsfs"},{"email_id":"raj#ghj.com","id":67,"mobile_no":"5632145412","name":"raj","relation":"xyz"}]
4)Now what i want to do:
In 1st cell i want to display,
name:asad mobile:1236547895 email:adas#faga.gs relation:dsfs
and in 2nd cell,
name:raj mobile:5632145412 email:raj#ghj.com relation:xyz
But i have no idea about how to do this.Please anyone can solve my issue. help will be appreciable.
I do like following way but it's not working.
a) Add a new file to the project, with the Objective-C class template. Name it EmergencyContactCell and make it a subclass of UITableViewCell.
b) then in EmergencyContactCell.h
#interface EmergencyContactCell : UITableViewCell
#property (nonatomic, weak) IBOutlet UILabel *name;
#property (nonatomic, weak) IBOutlet UILabel *email;
#property (nonatomic, weak) IBOutlet UILabel *mobile;
#property (nonatomic, weak) IBOutlet UILabel *relation;
c) then MainStoryboard.storyboard, select the prototypecell and in the Identity Inspector change its class to EmergencyContactCell
d) Then connect all outlets
e) I am using AFNetworking to take response from server, when i got response, after that i do like following way:
NSArray *ResponseArray = [NSJSONSerialization JSONObjectWithData: responseObject options: kNilOptions error: nil];
if (ResponseArray.count >0)
{
menuItems = [ResponseArray mutableCopy];
[yourTableviewname reloadData];
}
f) and for display it on cell,
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [menuItems count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"EmergencyContactCell";
//static NSString *simpleTableIdentifier = #"cell";
EmergencyContactCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
// NSDictionary *content = [menuItems objectAtIndex:indexPath.row];
// cell.textLabel.text = [NSString stringWithFormat:#"Name:%#, Mobile:%#, Email:%#, Relation:%#",content[#"name"],content[#"mobile_no"],content[#"email_id"],content[#"relation"]];
//
return cell;
}
I'm not getting what to do at last??
Step-1
No need of this
NSArray *ResponseArray = [NSJSONSerialization JSONObjectWithData: responseObject options: kNilOptions error: nil];
NSMutableArray *finalArray = [NSMutableArray array];
for (NSDictionary *temp in ResponseArray) {
[finalArray addObject:temp[#"name"]];
}
NSLog(#"%#",finalArray);
if(finalArray != nil && finalArray.count > 0){
menuItems=[NSArray arrayWithArray:finalArray];
NSLog(#"menu items: %#",menuItems);
}
else{
NSLog(#"zero values from server");
}
Simply Do like
NSArray *ResponseArray = [NSJSONSerialization JSONObjectWithData: responseObject options: kNilOptions error: nil];
if (ResponseArray.count >0)
{
menuItems = [ResponseArray mutableCopy];
[yourTableviewname reloadData];
}
Step-2
for your answer continution
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
NSDictionary *content = [menuItems objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"Name:%#, Mobile:%#, Email:%#, Relation:%#",content[#"name"],content[#"mobile_no"],content[#"email_id"],content[#"relation"]];
return cell;
}
Updated Answer
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"EmergencyContactCell";
EmergencyContactCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSDictionary *content = [menuItems objectAtIndex:indexPath.row];
cell.name.text = [NSString StringWithFormat:#"Name:%#",content[#"name"]];
cell.email.text = [NSString StringWithFormat:#"email:%#",content[#"email"]];
cell.mobile.text = [NSString StringWithFormat:#"mobile:%#",content[#"mobile"]];
cell.relation.text = [NSString StringWithFormat:#"relation:%#",content[#"relation"]];
return cell;
}
You need to do 2 things
After getting response set that into one NSArray. Declare NSArray
global one. And your code should be like
NSArray *arrayPersonalInfo = responseObject; // responseObject is response
got from server. Then call [tableView reloadData];
Now update your table view methods to
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return arrayPersonalInfo.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
NSDictionary *dictionaryMenu = [arrayPersonalInfo objectAtIndex:indexPath.row]; // It will save dictionary object of index
cell.textLabel.text = [NSString stringWithFormat:#"Name:%# Mobile:%# Email:%# Relation:%#",[dictionaryMenu valueForKey:#"name"],[dictionaryMenu valueForKey:#"mobile_no"],[dictionaryMenu valueForKey:#"email_id"],[dictionaryMenu valueForKey:#"relation"]];
cell.textLabel.numberOfLines = 0;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
return cell;
}
If needed add other table view methods like
heightForRowAtIndexPath and numberOfSections
If you prefer using storyboard, you can actually add a label into a prototype cell, make sure you set the prototype's cellIdentifier correctly to use it in codes. Then set a unique tag to your label. From your codes you can call viewWithTag from your cell's contentView to get the label and edit it's text property.

How to reload one table view row select then another tableview reload?

Below is my sample code. How to reload tblview(tableview)? Please help me.
#interface NewUIViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
#property (nonatomic, strong) NSMutableArray *dataArray;
#property (weak, nonatomic) IBOutlet UITableView *tblview;
- (IBAction)btnAddRow:(id)sender;
#property (weak, nonatomic) IBOutlet UITableView *tblviewProject;
#property (nonatomic, strong) NSMutableArray *projectArray;
#end
#interface NewUIViewController ()
{ }
#end
#implementation NewUIViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.dataArray = [[NSMutableArray alloc] initWithObjects:#"Tiger",#"Leopard",#"Snow Leopard",#"Lion",nil];
self.projectArray = [[NSMutableArray alloc] initWithObjects:#"test1",#"test12",#"test1 Leopard",#"test13",nil];];
self.tblview.delegate= self;
self.tblview.dataSource=self;
self.tblviewProject.delegate= self;
self.tblviewProject.dataSource =self;
self.tblviewProject.frame = CGRectMake(50, 150, 600, 600);
}
-(BOOL)shouldAutorotate
{
return YES;
}
- (NSUInteger ) supportedInterfaceOrientations
{
return (UIInterfaceOrientationMaskLandscape);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.tblview)
{
return [self.dataArray count];
}
else if (tableView == self.tblviewProject)
{
return [self.projectArray count];
}
return 0;
}
- (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.editingAccessoryType = YES;
if (tableView == self.tblview)
{
cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
}
else if (tableView == self.tblviewProject)
{
cell.textLabel.text = [self.projectArray objectAtIndex:indexPath.row];
}
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView == self.tblviewProject)
{
NSMutableDictionary *newDic = [[NSMutableDictionary alloc] init];
NSDictionary *rowchange = (NSDictionary *) [self.dataArray objectAtIndex:[self.projIndexPath intValue]];
[newDic addEntriesFromDictionary:rowchange];
[newDic setObject:pname forKey:project];
[self.tblview beginUpdates];
[self.dataArray replaceObjectAtIndex:[self.projIndexPath intValue] withObject:newDic];
[self.tblview reloadData];
[self.tblview endUpdates];
}
}
#end
In you didSelectRowAtIndexPath func ,What 's pname and projIndexPath
And self.dataArray is NSString array but you replaceObjectAtIndex with a dictionary, it 's not correct
I don't know what do you want?
Update: you function runing but don't mean it 's correct
In Cellforrowatindexpath you set
cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
But you replace a item in self.dataArray with a dictionary ==> you think, it 's working?
try:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView == self.tblviewProject)
{
[self.dataArray replaceObjectAtIndex:indexPath.row withObject:self.projectArray[indexPath.row]];
[self.tblview reloadData];
}
}
and replace pnam and projIndexPath as you want
AXXXXXXXXXXX
Update cellforrowat
- (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.editingAccessoryType = YES;
}
if (tableView == self.tblview)
{
cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
} else if (tableView == self.tblviewProject){
cell.textLabel.text = [self.projectArray objectAtIndex:indexPath.row];
}
return cell;
}
I's sure this working, when you reloaddata for tableview, cell is not nil, so, it 's not set data for cell

Why same nsmutablearray gives me valid value and a null on different functions used

I have a NSMutableArray with some objects of type Notes i.e. my class with attributes, iD,note,noteTitle.. I am using the notes array to populate a tableview, and on click, I am trying to open another controller view, to show that specific table row clicked
My code are :
when controller load:
- (void)viewDidLoad {
[super viewDidLoad];
Notes * myNotes =[[Notes alloc] init];
notes = [myNotes getMyNotes];
[super viewDidLoad];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [tableData 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];
}
NSString *title = [NSString stringWithFormat:#"%#...",((Notes *) [notes objectAtIndex:indexPath.row]).noteTitle ];
// here i am using my notes nsmutablearray from above method to populate tableview list of titles.. and it is populated fine.
cell.textLabel.text = title;
cell.imageView.image=[UIImage imageNamed:#"back.jpg"];
return cell;
}
Now when I click a row, I am trying to just see if, I will be getting title, body and it for that certain note..
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
long selectedRow = indexPath.row;
NSString *title = [NSString stringWithFormat:#"%#...",((Notes *) [notes objectAtIndex:selectedRow]).notes];
NSLog(#"%#",title);
}
But I am getting null this time...
why same code in above function is populating my table view but here not even logging it.
Thank you in advance....
You can try in didSelectRowAtIndexPath method
Notes *note = [[Notes alloc]init];
note = [notes objectAtIndex: indexPath.row];
NSString *title = [NSString stringWithFormat:#"%#...",note.notes];
NSLog(#"%#",title);
Hope it works.

Loading data from cell to detailView always show the last data

I have UITableView with some data from backend, I have everything in table,3 UILable and I will get that information from backend and I can show them in table row, when I click on row I want to have the same label in my detail view, but now, I have just one information in all my detail view, same information, just load the last row for all detailView,
would you please help me in this implementation,
Thanks in advance!
cellForRowAtIndexPath method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath
{
static NSString *CellIdentifier = #"BooksCell";
BooksCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell =[ [[NSBundle mainBundle] loadNibNamed:#"BooksCell" owner:nil options:nil]
lastObject];
}
_books = [server get_tests:10 offset:0 sort_by:0 search_for:#""];
_t = [NSMutableString stringWithFormat:#"%# ", [_books objectAtIndex:indexPath.row]];
NSString *testdata = _t;
_components = [testdata componentsSeparatedByString:#","];
NSLog(#"_components: %#",_components);
for (NSString *aComponent in _components) {
if ([aComponent hasPrefix:#"title"]) {
_subComponents = [aComponent componentsSeparatedByString:#":"];
_titleString = [_subComponents[1] stringByTrimmingCharactersInSet:[NSCharacterSet
characterSetWithCharactersInString:#"\""]];
}if ([aComponent hasPrefix:#"authors"]){
_subComponents = [aComponent componentsSeparatedByString:#":"];
_writerString = [_subComponents[1] stringByTrimmingCharactersInSet:[NSCharacterSet
characterSetWithCharactersInString:#"\""]];
}if ([aComponent hasPrefix:#"name"]){
_subComponents = [aComponent componentsSeparatedByString:#":"];
_publisherString = [_subComponents[1] stringByTrimmingCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#"\""]];
break;
}
}
cell.bookTitle.text = _titleString;
cell.writer.text = _writerString;
cell.publisher.text = _publisherString;
return cell;
}
didSelectRowAtIndexPath method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath
*)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
BooksDetailView *c = [[BooksDetailView alloc] init];
[self.booksTable addSubview:c.view];
c.bDetailTitle.text = _titleString;
c.bDetailWriter.text = _writerString;
c.bDetailPublisher.text = _publisherString;
}
_titleString, _writerString and _publisherString seem to be instance variables
of the table view controller, and these are overwritten in cellForRowAtIndexPath
each time a cell is displayed.
You have to use the indexPath in didSelectRowAtIndexPath to get the correct element
of your data source.
Note also that fetching all elements from the server in cellForRowAtIndexPath
is very ineffective, because this method is called frequently.
You should fetch the data once (e.g. in viewDidLoad) and assign
the fetched array to an instance variable or property of the view controller.
Then you can access the elements from the array in cellForRowAtIndexPath and in
didSelectRowAtIndexPath.
Add a property
#property (strong, nonatomic) NSArray *books;
to the view controller. Fetch the data in viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
self.books = [server get_tests:10 offset:0 sort_by:0 search_for:#""];
// ... other stuff ...
}
In cellForRowAtIndexPath you just get the element from the array.
Also, instead of all that string manipulation, you should use the model class
and property accessors generated by the Thrift API.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath
{
static NSString *CellIdentifier = #"BooksCell";
BooksCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell =[[[NSBundle mainBundle] loadNibNamed:#"BooksCell" owner:nil options:nil] lastObject];
}
YourModelClass *book = self.books[indexPath.row];
cell.bookTitle.text = book.title;
// ...
return cell;
}
And similarly in didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath
*)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
BooksDetailView *c = [[BooksDetailView alloc] init];
[self.booksTable addSubview:c.view]; // WHY THAT?
YourModelClass *book = self.books[indexPath.row];
c.bDetailTitle.text = book.title;
// ...
}

Resources