I am parsing a json to display the contents in the tableview. I have the array containing parsed json being populated in getReceivedData which is called after the UITAbleView Delegate methods. So it is problem in populating tableview as when the compiler attempts to populate it the array is not yet initialized.
- (void)getReceivedData:(NSMutableData *)data sender:(RestAPI *)sender{
NSError * error=nil;
NSArray *receivedData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSString *dictionaryKey=#"department";
NSString *predicateString=#"software";
NSPredicate *predicate=[NSPredicate predicateWithFormat:#" %K == %# ", dictionaryKey,predicateString];
NSArray *shortlisted=[receivedData filteredArrayUsingPredicate:predicate];
for(int i = 0; i<shortlisted.count; i++)
{
NSDictionary *detailItems=[shortlisted objectAtIndex:i];
NSString *name=[detailItems objectForKey:#"emp_name"];
NSString *designation=[detailItems objectForKey:#"designation"];
NSString *email=[detailItems objectForKey:#"email"];
NSString *phone_no=[detailItems objectForKey:#"phone_no"];
// NSString *image=[detailItems objectForKey:#"url_path"];
dictionary1=[NSMutableDictionary dictionaryWithObjectsAndKeys:
name, #"keyname",
designation, #"keydesignation",
email, #"keyid",
phone_no, #"keyphone",
nil];
[myObject1 addObject:dictionary1];
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section{
if(isfiltered==YES){
return [filteredArray count];
}
else{
return [myObject1 count];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath{
MyTableCell *cell=[tableView dequeueReusableCellWithIdentifier:#"myCell"];
if(!cell){
[tableView registerNib:[UINib nibWithNibName:#"MyTableCell" bundle:nil]
forCellReuseIdentifier:#"myCell"];
cell=[tableView dequeueReusableCellWithIdentifier:#"myCell"];
}
if(isfiltered==NO)
{
NSDictionary * tmpdict= [myObject objectAtIndex:indexPath.row];
cell.nameLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyname"]];
cell.designationLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keydesignation"]];
cell.idLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyid"]];
cell.phoneLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyphone"]];
cell.mainImg.image = [UIImage imageNamed:[tmpdict objectForKeyedSubscript:#"keyimage"]];
}
else{
NSDictionary * tmpdict= [filteredArray objectAtIndex:indexPath.row];
cell.nameLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyname"]];
cell.designationLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keydesignation"]];
cell.idLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyid"]];
cell.phoneLabel.text=[NSMutableString stringWithFormat:#"%#",[tmpdict objectForKeyedSubscript:#"keyphone"]];
cell.mainImg.image = [UIImage imageNamed:[tmpdict objectForKeyedSubscript:#"keyimage"]];
}
return cell;
}
This window was supposed to view the table
In a mutable dictionary first you have to give object then its key. You are doing wrong
for(int i = 0; i<shortlisted.count; i++)
{
NSDictionary *detailItems=[shortlisted objectAtIndex:i];
NSString *name=[detailItems objectForKey:#"emp_name"];
NSString *designation=[detailItems objectForKey:#"designation"];
NSString *email=[detailItems objectForKey:#"email"];
NSString *phone_no=[detailItems objectForKey:#"phone_no"];
dictionary1=[NSMutableDictionary dictionaryWithObjectsAndKeys:
name,#"keyname",
designation,#"keydesignation",
email,#"keyid",
phone_no,#"keyphone",
nil];
[myObject1 addObject:dictionary1];
}
Actually this is not correct way to intialize dictionary as you did, #"%#" is used %# is a placeholder in a format string for any object.
dictionary1=[NSMutableDictionary dictionaryWithObjectsAndKeys:
name,#"keyname",
designation,#"keydesignation",
email,#"keyid",
phone_no,#"keyphone",
nil];
Related
The top 3 cells in my tableview have a label that says the word 'Squirrels'. Is there a way to make it so that if a UILabel says 'Squirrels' in more than one cell in my table, to only show the first cell of the three?
E.g. if UILabel userName in tableviewCell is equal to #"Squirrels", only show one table
view cell in the table that contains Squirrels in the UILabel
Hope this makes sense. Thanks in advance!
EDIT: I've successfully retrieved the first array containing more than one common 'name' value (see edit to code below). That said, when I try and display these values (firstFoundObject) in my tableview I get the following crash error:
-[__NSDictionaryI objectAtIndex:]: unrecognized selector sent to instance 0x1c01a5a20 2017-10-03 23:01:51.728128-0700
pawswap[623:85420] *** Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[__NSDictionaryI
objectAtIndex:]: unrecognized selector sent to instance 0x1c01a5a20'
ViewController.m
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *nodeTitle = self.messages[0][#"name"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name == %#", nodeTitle];
NSArray *filteredArray = [self.messages filteredArrayUsingPredicate:predicate];
id firstFoundObject = nil;
firstFoundObject = filteredArray.count > 0 ? filteredArray.firstObject : nil;
NSMutableArray *firstObjects = firstFoundObject;
return [firstObjects count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *nodeTitle = self.messages[0][#"name"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name == %#", nodeTitle];
NSArray *filteredArray = [self.messages filteredArrayUsingPredicate:predicate];
id firstFoundObject = nil;
firstFoundObject = filteredArray.count > 0 ? filteredArray.firstObject : nil;
NSMutableArray *firstObjects = firstFoundObject;
static NSString *PointsTableIdentifier = #"MyMessagesCell";
MyMessagesCell *cell = (MyMessagesCell *)[tableView dequeueReusableCellWithIdentifier:PointsTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MyMessagesCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSDictionary *receivedSubjectLine = [firstObjects objectAtIndex:indexPath.row];
NSString *messageSubject = [receivedSubjectLine objectForKey:#"node_title"];
[cell.subjectLine setText:messageSubject];
NSDictionary *fromUser = [firstObjects objectAtIndex:indexPath.row];
NSString *userName = [fromUser objectForKey:#"name"];
[cell.senderName setText:userName];
NSDictionary *receivedBody = [firstObjects objectAtIndex:indexPath.row];
NSString *messageBody = [receivedBody objectForKey:#"body"];
[cell.fullMessage setText:messageBody];
NSDictionary *messageReceived = [firstObjects objectAtIndex:indexPath.row];
NSString *timeReceived = [messageReceived objectForKey:#"published at"];
NSLog(#"Message Received at %#", timeReceived);
[cell.receivedStamp setText:timeReceived];
return cell;
}
PREVIOUS
ViewController.m
#pragma mark - Table view data source
- (int)numberOfSectionsInTableView: (UITableView *)tableview
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.messages count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *PointsTableIdentifier = #"MyMessagesCell";
MyMessagesCell *cell = (MyMessagesCell *)[tableView dequeueReusableCellWithIdentifier:PointsTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MyMessagesCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSDictionary *receivedSubjectLine = [self.messages objectAtIndex:indexPath.row];
NSString *messageSubject = [receivedSubjectLine objectForKey:#"node_title"];
[cell.subjectLine setText:messageSubject];
NSDictionary *fromUser = [self.messages objectAtIndex:indexPath.row];
NSString *userName = [fromUser objectForKey:#"name"];
[cell.senderName setText:userName];
NSDictionary *receivedBody = [self.messages objectAtIndex:indexPath.row];
NSString *messageBody = [receivedBody objectForKey:#"body"];
[cell.fullMessage setText:messageBody];
NSDictionary *messageReceived = [self.messages objectAtIndex:indexPath.row];
NSString *timeReceived = [messageReceived objectForKey:#"published at"];
[cell.receivedStamp setText:timeReceived];
return cell;
}
Basically the problem you are getting is due to firstObject is of type Dictionary and you are type casting it to NSMutableArray. Please check below line:
id firstFoundObject = nil; firstFoundObject = filteredArray.count > 0
? filteredArray.firstObject : nil;
If you see you have filteredArray.firstObject as Dictionary in your application which you capture in firstFoundObject but later you are making it NSMutableArray type here:
NSMutableArray *firstObjects = firstFoundObject;
And later when you try to get here, it crashes
NSDictionary *receivedSubjectLine = [firstObjects
objectAtIndex:indexPath.row];
The correct - basic - version of your code should look like
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *PointsTableIdentifier = #"MyMessagesCell";
MyMessagesCell *cell = (MyMessagesCell *)[tableView dequeueReusableCellWithIdentifier:PointsTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MyMessagesCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
[cell.subjectLine setText:[self.recvMessage objectForKey:#"node_title"]];
[cell.senderName setText:[self.recvMessage objectForKey:#"name"]];
[cell.fullMessage setText:[self.recvMessage objectForKey:#"body"]];
[cell.receivedStamp setText:[self.recvMessage objectForKey:#"published at"]];
return cell;
}
Though it is not optimised but still it can do work for you.
COUNT ISSUE:
NSMutableDictionary *firstObjects = firstFoundObject;
return [firstObjects count];
In your code above you have inside the numberOfRowsInSection since you have firstFoundObject as dictionary so when you call [firstObjects count] which is a valid call and it returns the number of key in the dictionary.
You have modify it like :
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
NSInteger rowCount = filteredArray.count;
self.recvMessage = rowCount? filteredArray.firstObject: nil;
return rowCount? 1: 0;
}
and you have new data which actually stores the filtered object.
#property (nonatomic) NSDictionary *recvMessage;
Hope this helps.
Yes you can do it easily,
You will do it before run tableView,
for example :
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableDictionary* NameDictionary=[[NSMutableDictionary alloc] init];
NSString* PreviousName;
int oneTime=0;
for(int i=0;i<[self.messages count];i++){
NSDictionary *fromUser = [self.messages objectAtIndex: i];
NSString *userName = [fromUser objectForKey:#"name"];
if(oneTime==0)
{
PreviousName=userName;
[NameDictionary addObject:[self.messages objectAtIndex: i]];
oneTime=1;
}
if(oneTime!=0)
{
if([PreviousName isEqualToString: userName])
{
}
else{
[NameDictionary addObject:[self.messages objectAtIndex: i]];
}
PreviousName=userName;
}
}
}
When you ask to filter out cells with a senderName property equal to #"Squirrels", you're effectively asking to change your datasource after it has been set. This will cause problems in your numberOfRowsInSection method, which will return more rows than you need if any filtering takes place after the datasource is set.
As one of the comments to your answer suggests, "make a secondary array which contains unique elements of self.messages and work with this array." The array that makes up the datasource of the tableview should require no filtering. The tableview should just be able to present it.
If I had enough reputation to comment on the above answer, I would say that you're right that it doesn't work because self.messages doesn't change. Instead of collecting the "non-duplicate" objects in NameDictionary, consider collecting them in an NSMutableArray. This new, filtered array should be the datasource for your array. You may want to filter this array outside of this ViewController so that once the array arrives at this view controller it can just be assigned to self.messages.
If you're looking to exclude all duplicates, as opposed to just duplicates that appear next to each other, consider this answer.
I have used the below code to convert the JSON data(from SOAP service) to NSDictionary.
-(void)retriveFromSYSoapTool:(NSMutableArray *)_data{
NSLog(#"data: %#",_data);
NSArray *value = [_data valueForKey:#"GetDemoDataResult"];
NSError *error;
NSData *objData = [value[0] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",json);
}
Output
2017-04-04 13:03:51.085 SoapService[18444:588594] (
{
firstName = "1 Jhon";
lastName = Macay;
},
{
firstName = "2 William";
lastName = Proter;
},
{
firstName = "3 Joe";
lastName = Root;
},
{
firstName = "4 Brendon";
lastName = Haejoy;
},
{
firstName = "5 Jhon";
lastName = Snow;
},
{
firstName = "6 Theon";
lastName = Greyjoy;
}
)
Do I need to convert this to any other? or how could I bind the above output in UITableView?
To work with table view you need array
Checkout this simple table view tutorial
It should be like this
Declare jsonArray in your .h file
#property (strong, nonatomic) NSMutableArray *jsonArray;
Add below line viewDidLoad
self.jsonArray = [[NSMutableArray alloc]init];
-(void)retriveFromSYSoapTool:(NSMutableArray *)_data{
NSLog(#"data: %#",_data);
NSArray *value = [_data valueForKey:#"GetDemoDataResult"];
NSError *error;
NSData *objData = [value[0] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",son);
[self.jsonArray addObject:[[json objectForKey:#"firstname"]stringByAppendingString:[json objectForKey:#"lastname"]];
[tableViewName reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.jsonArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
cell.textLabel.text = [self.jsonArray objectAtIndex:indexPath.row];
return cell;
}
take one NSMutuableArray and add dictionary to this array like
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject: json];
//Than Reload Tableview
Note: Declare array Globally to access in your class
tableview display data like
cell.label.text = [[array objectAtIndex:indexPath.row]valueForKey:#"firstName"];
Store json data into Global Declare NSArray.
-(void)retriveFromSYSoapTool:(NSMutableArray *)_data{
NSLog(#"data: %#",_data);
NSArray *value = [_data valueForKey:#"GetDemoDataResult"];
NSError *error;
NSData *objData = [value[0] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",json);
DataArray = [NSArray arrayWithObjects:json, nil];
[tableView reloadData];
}
Here DataArray is Globally Declare NSArray Object;
Now Write UITableView DataSource Method.
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return DataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"jsoncell" forIndexPath:indexPath];
NSDictionary *dict = DataArray[indexPath.row];
NSString *output = [NSString stringWithFormat:#"%# %#",dict[#"firstName"],dict[#"lastName"]];
cell.textLabel.text = output;
return cell;
}
I have a api please look at this first.
{"result":"Successful","data":[{"price":"100.00","packs":"Garbage Bags","pack_id":"1","products":[{"quantity":"15","image":"1454651885ECOWGBS_03.jpg"},{"quantity":"15","image":"1454652017ECOWGBM_03.jpg"},{"quantity":"15","image":"1454652132ECOWGBL_02.jpg"}]},{"price":"200.00","packs":"Party","pack_id":"2","products":[{"quantity":"50","image":"1454589144USI_6819.jpg"},{"quantity":"50","image":"1454587252ecow240b_01.jpg"},{"quantity":"50","image":"1454499020ecow10rp_01.jpg"}]},{"price":"300.00","packs":"Travel","pack_id":"3","products":[{"quantity":"25","image":"1454589144USI_6819.jpg"},{"quantity":"25","image":"1454588615ecow103crp_01.jpg"},{"quantity":"25","image":"1455532004ECOWCLAM1_03.jpg"}]},{"price":"400.00","packs":"Kids","pack_id":"4","products":[{"quantity":"25","image":"1454499251ecow6rp_01.jpg"},{"quantity":"25","image":"1454588417ecow5ct_01.jpg"},{"quantity":"25","image":"1454587802ecow340b_01.jpg"}]}]}
Number of cell is generated demand upon the number of packs in api. For example in this api four pack are there so i parse the total number of pack and add it to array and than add that array in uicollectionview like this.
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [packdetail count];
}
Till now all thing working fine but when i tried to pass quantity in products data on uilabel it display on every cell and for only first products array. but i need to pass first products array on first cell and second product array on second cell and so on. Here is my code please look at this.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSArray *dataarray = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:#"data"];
[packdetail removeAllObjects];
for (NSDictionary *tmp in dataarray)
{
NSMutableDictionary *temp = [NSMutableDictionary new];
[temp setObject:[tmp objectForKey:#"packs"] forKey:#"packs"];
[temp setObject:[tmp objectForKey:#"pack_id"] forKey:#"pack_id"];
[packdetail addObject:temp];
NSLog(#"packdetail %#", packdetail);
productarray = [tmp objectForKey:#"products"];
NSLog(#"products %#", productarray);
for (NSDictionary *product in productarray) {
NSMutableDictionary *temp2 =[NSMutableDictionary new];
[temp2 setObject:[product objectForKey:#"quantity"]forKey:#"quantity"];
[quantity addObject:temp2];
}
}
if (packdetail)
{
[_subscriptioncollectionview reloadData];
}
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [packdetail count];
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
SubscriptionCell *cell = (SubscriptionCell*)[collectionView dequeueReusableCellWithReuseIdentifier:#"cell" forIndexPath:indexPath];
cell.packname.text = [[packdetail objectAtIndex:indexPath.row] objectForKey:#"packs"];
cell.productname.text = [[quantity objectAtIndex:indexPath.row] objectForKey:#"quantity"];
return cell;
}
Your answer is
for (NSDictionary *tmp in dataarray)
{
NSMutableDictionary *temp = [NSMutableDictionary new];
[temp setObject:[tmp objectForKey:#"packs"] forKey:#"packs"];
[temp setObject:[tmp objectForKey:#"pack_id"] forKey:#"pack_id"];
[packdetail addObject:temp];
NSLog(#"packdetail %#", packdetail);
productarray = [tmp objectForKey:#"products"];
NSLog(#"products %#", productarray);
for (NSDictionary *product in productarray) {
NSMutableDictionary *temp2 =[NSMutableDictionary new];
[temp2 setObject:[product objectForKey:#"quantity"]forKey:#"quantity"];
[quantity addObject:temp2];
}
}
Change to
for (NSDictionary *tmp in dataarray)
{
NSMutableDictionary *temp = [NSMutableDictionary new];
[temp setObject:[tmp objectForKey:#"packs"] forKey:#"packs"];
[temp setObject:[tmp objectForKey:#"pack_id"] forKey:#"pack_id"];
NSLog(#"packdetail %#", packdetail);
productarray = [tmp objectForKey:#"products"];
NSLog(#"products %#", productarray);
for (NSDictionary *product in productarray) {
[temp setObject:[product objectForKey:#"quantity"]forKey:#"quantity"];
}
[packdetail addObject:temp];
}
Display in cell
cell.label.text = [[packdetail objectAtIndex:indexPath.row] objectForKey:#"quantity"];;
NSArray *array = [JsonArray];
in CellForRowAtIndexPath:
cell.label.text = [[[array objectAtIndex:indexPath.section] objectForKey:#"products"][indexpath.row]valueForkey #"quantity"];
I need to filter data in UITableview by text entered in UISearchbar. I followed this example but there data in NSMutableArray and I can't alter it under my requirements. My data is NSMutableDictionary. I'm stuck on this for long time.
My data:
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [[documentPaths lastObject] stringByAppendingPathComponent:#"data.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSMutableDictionary *resultDic = [[NSMutableDictionary alloc] init];
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
NSDictionary *myDict = [NSDictionary dictionaryWithContentsOfFile:path];
sectionKeys = [NSMutableArray new];
sectionsTitle = [NSMutableArray new];
NSArray *tableArray = [myDict objectForKey:#"Black"];
[resultArray addObject:#"Black"];
[resultDic setValue:tableArray forKey:#"Black"];
[sectionsTitle addObject:[NSString stringWithFormat:#"%#", [tableData valueForKey:#"Black"]]];
[sectionCord addObject:[NSString stringWithFormat:#"%#", [tableData valueForKey:#"Coordinates"]]];
[sectionKeys addObject:#"Section1"];
self.tableData = resultDic;
self.sectionsTitle = resultArray;
[myTable reloadData];
My table:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return sectionKeys.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [sectionKeys objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int rowCount;
if(self.isFiltered)
rowCount = [[filteredTableData objectForKey:[sectionsTitle objectAtIndex:section]] count];
else
rowCount = [[tableData objectForKey:[sectionsTitle objectAtIndex:section]] count];
return rowCount;
}
- (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(isFiltered){
NSDictionary *dict = [[filteredTableData objectForKey:[sectionsTitle objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%#", [dict objectForKey:#"Name"]];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", [dict objectForKey:#"Address"]];
}
else{
NSDictionary *dict = [[tableData objectForKey:[sectionsTitle objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%#", [dict objectForKey:#"Name"]];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", [dict objectForKey:#"Address"]];
}
return cell;
}
My search:
#pragma mark - SearchBar Delegate -
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text{
if(text.length == 0)
{
isFiltered = FALSE;
NSLog(#"false");
}
else
{
isFiltered = true;
NSLog(#"true");
filteredTableData = [[NSMutableDictionary alloc] init];
for (MyAnnotation* ann in tableData)
{
NSRange nameRange = [ann.title rangeOfString:text options:NSCaseInsensitiveSearch];
NSRange descriptionRange = [ann.description rangeOfString:text options:NSCaseInsensitiveSearch];
if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound)
{
[filteredTableData addObject:ann];
//error
}
}
}
[myTable reloadData];
}
First of all, you need to create a state/flag for the controller/data source, in order for it to know weather you are in search/filter mode.
Then, if you are in search mode, point the data source methods to the filteredArray.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
int numberOfSections = 0;
if (_searchMode)
{
numberOfSections = self.filteredDataDict.allKeys.count;
}
else
{
numberOfSections = self.tableData.allKeys.count;
}
return numberOfSections;
}
Hope it's understood.
I would have thought 'self.data=' would retain the autorelease NSMutableArray objects and the NSMutableDictionary objects it contains, but eventually I get EXC_BAD_ACCESS when the table's cellForRowAtIndexPath method tries to access the NSDictionaries in self.data.
#property (strong, nonatomic) NSMutableArray *data;
- (void) updateReceivedData:(NSData *) jsonData
{
NSMutableArray *fetchedData = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
self.data = [self convertDates:fetchedData withFormat:kMySQLDateTimeFormat];
[self.tableView reloadData];
}
}
- (NSMutableArray*) convertDates:(NSMutableArray *) array withFormat:(NSString *) format
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:format];
NSMutableArray *newArray = [NSMutableArray arrayWithArray:array];
for (NSMutableDictionary *dict in newArray)
{
for (id key in dict.allKeys)
{
if ([[dict objectForKey:key] isKindOfClass:[NSString class]])
{
NSString *value = [dict objectForKey:key];
NSDate *date = [dateFormatter dateFromString:value];
if (date) [dict setObject:date forKey:key];
}
}
}
[dateFormatter release];
return newArray;
}
BAD_ACCESS HERE thrown here between the NSLogs.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSLog (#"Cell was nil");
cell = [[[CustomCell alloc] init] autorelease];
}
NSDictionary *dict = [[NSDictionary alloc] init];
if (_isFiltered){
dict = [self.filteredData objectAtIndex:indexPath.row];
} else {
dict = [self.data objectAtIndex:indexPath.row];
}
NSLog (#"Filling Label 1");
cell.IDLabel.text = [[dict objectForKey:#"Id"] stringValue];
NSLog (#"Filling Label 2");
cell.firstNameLabel.text = [dict objectForKey:#"firstName"];
[dict release];
return cell;
}
Turn on zombies and see if it catches the problem (EXC_BAD_ACCESS does not necessarily mean an over-released object, but it might).
What happens to the absolute value of the retain count of an object is irrelevant.
However, a strong property implies that the object is retained, yes, if you assign through the setter (i.e. self.data = ... and not _data = ...).
Why are you releasing the dict in cellForRowAtIndexPath: . Eventhough you allocate dict, you are assigning another pointer which is an object from filteredData or data. Just remove the [data release] and while declaring data assign it as nil
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSLog (#"Cell was nil");
cell = [[[CustomCell alloc] init] autorelease];
}
// **As you will be assigning the object from filteredData/data, don't allocate here**
NSDictionary *dict = nil;
if (_isFiltered){
dict = [self.filteredData objectAtIndex:indexPath.row];
} else {
dict = [self.data objectAtIndex:indexPath.row];
}
NSLog (#"Filling Label 1");
cell.IDLabel.text = [[dict objectForKey:#"Id"] stringValue];
NSLog (#"Filling Label 2");
cell.firstNameLabel.text = [dict objectForKey:#"firstName"];
// **Release not required as you didn't allocate**
//[dict release];
return cell;
}