I make dictionary in iOS, I get data from JSON url. I have problem with correctly display result of word from SearchBar. For example when I type something in searchBar and click on some result , always display value of first result.
Below I put my screen to present this problem.
On the second screen I click on Ruby on Rails and show me first of result "Objective C", why (Objective C is a first result in JSON file)?
And it's my code: http://pastebin.com/EPVTpF9U
#pragma mark - Navigation
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([[segue identifier] isEqualToString:#"pushDetailView"]){
NSIndexPath * indexPath = [self.tableView indexPathForSelectedRow];
DetailViewController *modalVC = (DetailViewController*)segue.destinationViewController;
modalVC.detailArray = [self.finalResultArray objectAtIndex:indexPath.row];
}
}
#pragma mark - UISearchDisplayDelegate
// register a cell reuse identifier for the search results table view
-(void)searchDisplayController:(UISearchDisplayController *)controller
didLoadSearchResultsTableView:(UITableView *)tableView {
[tableView registerClass:[UITableViewCell class]
forCellReuseIdentifier:#"Cell"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(tableView == self.tableView){
return self.finalResultArray.count;
}else{
return self.results.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdetifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdetifier forIndexPath:indexPath];
if(!cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdetifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if(tableView == self.tableView){
cell.textLabel.text = [[self.finalResultArray objectAtIndex:indexPath.row] objectForKey:#"expression"];
cell.detailTextLabel.text = [[self.finalResultArray objectAtIndex:indexPath.row] objectForKey:#"meaning"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
else{
cell.textLabel.text = [[self.results objectAtIndex:indexPath.row] objectForKey:#"expression"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:180/255.0
green:138/255.0
blue:171/255.0
alpha:0.5];
cell.selectedBackgroundView = customColorView;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self performSegueWithIdentifier:#"pushDetailView" sender:self];
}
- (void)simpleJsonParsing
{
//-- Make URL request with server
NSHTTPURLResponse *response = nil;
NSString *jsonUrlString = [NSString stringWithFormat:#"https://uidictionary.herokuapp.com/phrases.json"];
NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//-- Get request and response though URL
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
//-- JSON Parsing
NSArray *result = [[NSJSONSerialization JSONObjectWithData:responseData options:
NSJSONReadingMutableContainers error:nil] objectForKey:#"phrases"];
[self.finalResultArray removeAllObjects];
for (NSMutableDictionary *tmp in result)
{
NSMutableDictionary *temp = [NSMutableDictionary new];
[temp setObject:[tmp objectForKey:#"expression"] forKey:#"expression"];
[temp setObject:[tmp objectForKey:#"meaning"] forKey:#"meaning"];
[self.finalResultArray addObject:temp];
}
if (self.finalResultArray){
[self.tableView reloadData];
}
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
self.results = [self.finalResultArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"%K contains[c] %#", #"expression", searchController.searchBar.text]];
NSLog(#"Filterd Array:-%#", self.results);
// hand over the filtered results to our search results table
UITableViewController *tableController = (UITableViewController *)self.searchController.searchResultsController;
tableController.tableView.dataSource = self;
tableController.tableView.delegate = self;
[tableController.tableView reloadData];
}
Just replace Bellow Code :-
self.results = [self.finalResultArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"%K BEGINSWITH[c] %#", #"expression", searchController.searchBar.text]];
#mechu911
Replace your method with below code.
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([[segue identifier] isEqualToString:#"pushDetailView"]){
NSIndexPath * indexPath = [self.tableView indexPathForSelectedRow];
DetailViewController *modalVC = (DetailViewController*)segue.destinationViewController;
modalVC.detailArray = [self.result objectAtIndex:indexPath.row];
}
}
but you have to put check like
if(tableView == self.tableView){
modalVC.detailArray = [self.finalResultArray objectAtIndex:indexPath.row];}
else{modalVC.detailArray = [self.result objectAtIndex:indexPath.row];}
Related
I'm having a weird issue on UITableView delete action since iOS 11.
Here's the relevant TableView code :
#implementation ChatMessageListViewController(TableView)
#pragma mark - table view datasource/delegate
- (NSArray<UITableViewRowAction *> *) tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
NSMutableArray *rowActions = [NSMutableArray array];
UITableViewRowAction *delete = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:#"Delete" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
[self deleteMessageAtIndexPath:indexPath];
}];
delete.backgroundColor = [UIColor redColor];
[rowActions addObject:delete];
return [rowActions copy];
}
- (void) deleteMessageAtIndexPath:(NSIndexPath *)indexPath {
NSString *threadID = [[self.messageArray objectAtIndex:indexPath.row] objectForKey:#"threadID"];
[self.tableView beginUpdates];
[self.messageArray removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView endUpdates];
#weakify(self);
[UIUtil showLoadingHudWithText:WELocalString(#"message_remove_thread_loading_text", #"Deleting...", #"删除中...")];
[[AsyncUtil sharedInstance] dispatch_background_network:^{
DBManager *db = [[DBManager alloc] init];
[db deletetableData:[NSString stringWithFormat:#"singleChat WHERE threadID = '%#' ",threadID] ];
[[MemChatThreadMessages sharedInstance] removeThread:threadID];
NSDictionary * result = [Network deleteChatThread:threadID forEmail:[WEUtil getEmail]];
[[AsyncUtil sharedInstance] dispatch_main:^{
[UIUtil hideLoadingHuds];
#strongify(self);
if(self == nil) return ;
if([result[#"result"] isEqualToString:#"success"]){
}else{
[UIUtil showErrorMessage:WELocalString(#"message_remove_thread_error", #"Cannot delete this thread", #"不能删除该会话!")];
}
[self.tableView reloadData];
}];
}];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [self.messageArray count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSDictionary *messageInfo = [self.messageArray objectAtIndex:indexPath.row];
if ([(NSString *)[messageInfo objectForKey:#"isAnnouncement"] isEqualToString:#"1"]) {
return 80;
}else if ([[messageInfo objectForKey:#"chatTag"] isValidString]){
return 80;
}else if([self isSpecialMessage:messageInfo]){
return 80;
}else{
return 67;
}
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"message";
if(self.events == nil){
NSDictionary * d = [WEUtil getMyEventListCache];
self.events = [[NSMutableDictionary alloc] init];
for(NSDictionary * eventSummary in d[#"events"]){
NSString * eventID = eventSummary[#"eventid"];
[self.events setObject:eventSummary forKey:eventID];
}
}
UserMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil){
cell = [[UserMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
if(indexPath.row >= [self.messageArray count]){
TERMINATE_WITH_NIL_CELL;
}
NSDictionary *messageInfo = [self.messageArray objectAtIndex:indexPath.row];
if(![self isSpecialMessage:messageInfo]){
[cell configureCellWithMessageDict:messageInfo];
}else{
[cell configureCellWithNewMessageDict:messageInfo withEvents:self.events];
}
return cell;
}
#pragma mark - Navigation
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *msgThreadDict = [self.messageArray objectAtIndex:indexPath.row];
if(![self isSpecialMessage:msgThreadDict]){
[self tableView:tableView didSelectNormalRowAtIndexPath:indexPath];
}else{
NSString * event = msgThreadDict[#"event"];
if([event isValidString]){
if([event isEqualToString:#"no_event_messages"]){
[UIUtil showErrorMessage:#"no event id"];
}else{
[BackendTracking trackingWithAction:#"open_special" withLabel:#"threads_list"];
SpecialTopicListViewController * special = [[SpecialTopicListViewController alloc] init];
special.tracking_src = #"tab";
[self.navigationController pushViewController:special animated:YES];
}
}
}
}
-(void) tableView:(UITableView *)tableView didSelectNormalRowAtIndexPath:(NSIndexPath *)indexPath{
NSDictionary *msgThreadDict = [self.messageArray objectAtIndex:indexPath.row];
NSString *threadID = [msgThreadDict objectForKey:#"threadID"];
NSString *jid = [msgThreadDict objectForKey:#"jid"];
[GATracking trackCategory:#"message" withAction:#"thread_list_item_click" withLabel:threadID];
[[MemChatThreadMessages sharedInstance] setCurrentThreadID:threadID];
PrivateMessageViewController * chatVC = [[PrivateMessageViewController alloc] init];
chatVC.threadID = threadID;
chatVC.targetJID = jid;
chatVC.targetName = [msgThreadDict objectForKey:#"name"];
chatVC.unreadMsgNumber = [[self.messageArray objectAtIndex:indexPath.row][#"unreadCnt"] integerValue];
if ([(NSString *)[msgThreadDict objectForKey:#"isGroup"] isEqualToString:#"1"]) {
chatVC.isGroup = YES;
}else{
chatVC.isGroup = NO;
}
chatVC.src = #"list";
WELogInfo(#"click message");
[self.navigationController pushViewController:chatVC animated:YES];
}
#end
With the update and the changes using those trailing swipe actions there is another View appended before each time I delete an entry (until it doesn't work anymore). I've tried disabling the full trail or implementing iOS 11 trailingSwipeActionsConfigurationForRowAtIndexPath but I can't resolve this issue so far.
Do you see something wrong in the code? The main controller code is in another file.
Try reloading after you delete, after this line
[self.tableView endUpdates];
I think you removed the data from messageArray but as you are not reloading just after that so table view count is still 2 and you are reloading inside the block which might be taking time.
And one more thing you already removing data from messageArray, and then removing from db, So if you fail to remove it from db you are showing its not removed but for user it will be removed, as its no longer in message array
How should I use search controller instead of searchDisplayController in tableView method
I have an example code here
if (tableView == self.searchDisplayController.searchResultsTableView)
Hhere I am getting error on this line it says searchDisplayController is deprecated.
#implementation LocationsViewController
{
NSArray *_park;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.searchResult = [NSMutableArray arrayWithCapacity:[self->_park count]];
// Create a new JSONLoader with a local file URL
JSONLoader *jsonLoader = [[JSONLoader alloc] init];
NSURL *url = [[NSBundle mainBundle] URLForResource:#"park" withExtension:#"json"];
// Load the data on a background queue...
// As we are using a local file it's not really necessary, but if we were connecting to an online URL then we'd need it
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
_park = [jsonLoader locationsFromJSONFile:url];
// Now that we have the data, reload the table data on the main UI thread
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES];
});
}
//Just before showing the LocationDetailViewController, set the selected Location object
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
LocationDetailViewController *vc = segue.destinationViewController;
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
vc.location = [_park objectAtIndex:indexPath.row];
}
#pragma mark - Table View Controller Methods
//UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"LocationCell"];
Location *location = [_park objectAtIndex:indexPath.row];
cell.textLabel.text = location.name;
cell.detailTextLabel.text = location.address;
// cell.detailTextLabel.text = location.ide;
cell.imageView.image = [UIImage imageNamed:#"location_image"];
///////////////////
if (tableView == self.searchDisplayController.searchResultsTableView)
{
cell.textLabel.text = [self.searchResult objectAtIndex:indexPath.row];
}
else
{
cell.textLabel.text = self->_park[indexPath.row];
}
/////////////////
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//////////////////////////////////////////////
if (tableView == self.searchDisplayController.searchResultsTableView)
{
return [self.searchResult count];
}
else
{
return [self->_park count];
}
//////////////////////////////////////////////
return [_park count];
}
/////////////////////////////////////////////////
- (void)filterContentForSearchText:(NSString*)searchText scope: (NSString*)scope
{
[self.searchResult removeAllObjects];
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"SELF contains[c] %#", searchText];
self.searchResult = [NSMutableArray arrayWithArray: [self->_park filteredArrayUsingPredicate:resultPredicate]];
}
-(BOOL)searchDisplayController:(UISearchController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope: [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
#end
I believe you have declared a UISearchController by passing nil as a parameter to searchResultsController. So your same tableView is being used as searchResultsController of UISearchController
like
let searchController = UISearchController(searchResultsController: nil)
or
UISearchController searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
I hope all you want to do now is to distinguish whether UISeacrhController is active or it's your tableView so that you can show different cell for them :)
If so,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"LocationCell"];
Location *location = [_park objectAtIndex:indexPath.row];
cell.textLabel.text = location.name;
cell.detailTextLabel.text = location.address;
// cell.detailTextLabel.text = location.ide;
// cell.imageView.image = [UIImage imageNamed:#"location_image"];
if (searchController.active)
{
cell.textLabel.text = [self.searchResult objectAtIndex:indexPath.row];
}
else
{
cell.textLabel.text = self->_park[indexPath.row];
}
/////////////////
return cell;
}
My answer in comment if (tableView == self.yourSearchController. searchResultsController) would have worked if you had instantiated a different tableView controller and provided as SearchResultsController for UISearchController
But because you have specified nil in your init of UISearchControllersame tableView instance will be used as SearchResultsController. So comparing will result in always yes :)
Rather, you can depend on active property of UISearchController and check in what context tableView is being used and handle it appropriately :)
Hope I made my point clear :) Happy coding :)
I am developing an ios app..Click on button to Pass The Json Array To other UiViewController TableView To Show The Data In TableView..In TableView Array Data Pass on NSDictionary and to Use Dictionary Object. Error is [__NSCFDictionary objectAtIndex:]: Unrecognised selector sent to instance 0x7b115560']...Thanks In Advance
// Button Click
BBAuthorDetailViewController *BBAuthorDetail =[[UIStoryboard storyboardWithName:#"Main" bundle:nil]instantiateViewControllerWithIdentifier:#"BBAuthorDetail"];
[BBAuthorDetail setSelectionType:BBSelectionAuthorName];
_serverObj = [[Server alloc]init];
[_params setObject:_adDetailsObj.authorDetail forKey:#"author"];
[_serverObj BBAuthorNameWithParams:_params];
// BBAuthorDetail.data=resultsArray;
//NSIndexPath *indexPath = [BBAuthorDetail.tableview indexPathForSelectedRow];
BBAuthorDetail.data = [resultsArray objectAtIndex:indexPath.row];
NSLog(#"%#",resultsArray);
//[BBAuthorDetail setManagedObjectContext:self.managedObjectContext];
[self.navigationController pushViewController:BBAuthorDetail animated:YES];
UIViewController Table TO Show Data
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _data.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = [NSString stringWithFormat:#"Cell-%li", (long)indexPath.row];
BBAdsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
// AdDetails *_adDetailsObj = (AdDetails *)[_data objectAtIndex:indexPath.row];
// NSDictionary *dic = [_data objectAtIndex:indexPath.row];
//AdDetails *_adDetailsObj = [[AdDetails alloc]init];
if (cell == nil) {
cell = [[BBAdsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
cell.row = indexPath.row;
//[cell setDelegate:self];
}
// Error Part
NSDictionary *dic = [_data objectAtIndex:0];
cell.textLabel.text = [dic objectForKey:#"post_author"];
return cell;
}
When I type letters into my Search I get lag for about 4secs and can`t do anything. Everything others work good. UISearchDisplayController find me what I want, segue works good . I am not sure if it is about memory or some mistake in my code. Can anyone help me? Thanks
My code
TableViewController.m
#implementation TableViewController
#synthesize colorsTable;
#synthesize searchBar;
#synthesize searchController;
#synthesize searchResults;
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showDetail"]) {
{
DetailViewController *sdvc = (DetailViewController *)[segue destinationViewController];
if(self.searchDisplayController.active) {
NSIndexPath *indexPath = [[self tableView] indexPathForSelectedRow];
PFObject *object = [self.objects objectAtIndex:indexPath.row];
object = (PFObject *)[[self searchResults]objectAtIndex:[[[[self searchDisplayController]searchResultsTableView]indexPathForSelectedRow]row]];
sdvc.detailItem = object;
} else {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
PFObject *object = [self.objects objectAtIndex:indexPath.row];
DetailViewController *detailViewController = [segue destinationViewController];
detailViewController.detailItem = object;
}
}
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self performSelector:#selector(runThisMethod) withObject:nil afterDelay:1.9f];
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
self.tableView.tableHeaderView = self.searchBar;
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
self.searchController.delegate = self;
CGPoint offset = CGPointMake(0, self.searchBar.frame.size.height);
self.tableView.contentOffset = offset;
self.searchResults = [NSMutableArray array];
-(void)filterResults:(NSString *)searchTerm {
[self.searchResults removeAllObjects];
PFQuery *query = [PFQuery queryWithClassName: self.parseClassName];
[query whereKeyExists:#"MestoName"]; //this is based on whatever query you are trying to accomplish
[query whereKey:#"MestoName" containsString:searchTerm];
NSArray *results = [query findObjects];
NSLog(#"%#", results);
NSLog(#"%u", results.count);
[self.searchResults addObjectsFromArray:results];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterResults:searchString];
return YES;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.tableView) {
//if (tableView == self.searchDisplayController.searchResultsTableView) {
return self.objects.count;
} else {
return self.searchResults.count;
}
}
- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
{
tableView.rowHeight = 90.0f;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
static NSString *uniqueIdentifier = #"colorsCell";
CustomCell *cell = nil;
cell = (CustomCell *) [self.tableView dequeueReusableCellWithIdentifier:uniqueIdentifier];
[cell.imagevieww setImageWithURL:[NSURL URLWithString:[object objectForKey:#"ImageURL"]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
cell.cellTitle.text = [object objectForKey:#"MestoName"];
cell.cellDescript.text = [object objectForKey:#"MestoSubname"];
if (!cell) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"colorsCell" owner:nil options:nil];
for (id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[CustomCell class]])
{
cell = (CustomCell *)currentObject;
break;
}
}
}
if (tableView == self.tableView) {
cell.cellTitle.text = [object objectForKey:#"MestoName"];
} else {
PFUser *obj2 = [self.searchResults objectAtIndex:indexPath.row];
PFQuery *query = [PFQuery queryWithClassName:#"Mesta"];
PFObject *searchedUser = [query getObjectWithId:obj2.objectId];
NSString *boottext = [searchedUser objectForKey:#"MestoName"];
cell.cellTitle.text = boottext;
NSString *bootsubtext = [searchedUser objectForKey:#"MestoSubname"];
cell.cellDescript.text = bootsubtext;
NSString *bootimage = [searchedUser objectForKey:#"ImageURL"];
[cell.imagevieww setImageWithURL:[NSURL URLWithString:bootimage]];
NSLog(#"Content: %#", boottext);
}
return cell;
}
#end
For everyone, who have the same problem. I have got already the solution. I rewrote all my code and it is finally working.
Here`s the code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
NSString *uniqueIdentifier = #"MainCell";
CustomCell3 *cell = nil;
cell = (CustomCell3 *) [self.tableView dequeueReusableCellWithIdentifier:uniqueIdentifier];
if (!cell) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"MainCell" owner:nil options:nil];
for (id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[CustomCell3 class]])
{
cell = (CustomCell3 *)currentObject;
break;
}
}
}
if (tableView == self.tableView) {
cell.MainTitle.text = [object objectForKey:#"CountryTitle"];
cell.DescriptTitle.text = [object objectForKey:#"DescriptTitle"];
[cell.FlagTitle setImageWithURL:[NSURL URLWithString:[object objectForKey:#"ImaURL"]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
};
if(tableView == self.searchDisplayController.searchResultsTableView) {
PFObject *searchedUser = [self.searchResults objectAtIndex:indexPath.row];
NSString *content = [searchedUser objectForKey:#"CountryTitle"];
NSString *desco = [searchedUser objectForKey:#"DescriptTitle"];
cell.DescriptTitle.text = desco;
cell.MainTitle.text = content;
NSString *image = [searchedUser objectForKey:#"ImaURL"];
[cell.FlagTitle setImageWithURL:[NSURL URLWithString:image]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
};
return cell;
}
I am trying to implement search bar in my custom Contacts Book. I created NSDictionary for search data and added to my dictionary 4 mutable arrays, include
names, last name, phone types, phone numbers.
When I am trying to search in NSDictionary, my app is crashing on cell create. And When I am searching by one array only (from dictionary valueforkey or directly from array) it's working partially, but taking another strings (for example last name) always from the first contact in the list. Bacause not all parameters in a loop, So I have to search by every parameter to get right first name and last name in my contacts.
here is my code:
#pragma mark SEARCH_BAR
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[self.tableSearchBar resignFirstResponder];
}
-(void)searchBar:(UISearchBar *)serachBar textDidChange:(NSString *)searchText {
[filteredStrings removeAllObjects];
if (searchText.length == 0) {
isFiltered = NO;
} else {
isFiltered = YES;
//here aim creating NSDictionary with 4 Mutable Arrays
NSDictionary *filteredContacts = [NSDictionary dictionaryWithObjectsAndKeys:
contacts.firstNames, #"First Name",
contacts.lastNames, #"Last Name",
contacts.phoneTypes, #"Phone Type",
contacts.phoneNumbers, #"Phone Numbers",
nil];
//[filteredStrings addObject:filteredContacts];
for (NSString *str in filteredContacts) { // in this case for (NSString *str in [filteredContacts valueForKey:#"First Name"]) all working partially
NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (stringRange.location != NSNotFound) {
filteredStrings = [[NSMutableArray alloc]init];
[filteredStrings addObject:str];
}
}
}
[self.contactsTableView reloadData];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (isFiltered) {
return [filteredStrings count];
}
return [contacts.firstNames count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"Cell";
abCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (!cell) {
cell = [tableView dequeueReusableCellWithIdentifier:cellID];
}
if (!isFiltered) {
cell.firstNameLabel.text = [contacts.firstNames objectAtIndex:indexPath.row];
cell.lastNameLabel.text = [contacts.lastNames objectAtIndex:indexPath.row];
cell.contactImage.image = [UIImage imageNamed:#"NOIMG.png"];
} else {
cell.firstNameLabel.text = [filteredStrings objectAtIndex:indexPath.row]; // Here my app is crashing when trying to search by all nsdictionary.
cell.lastNameLabel.text = [filteredStrings objectAtIndex:indexPath.row];
//cell.contactImage.image = [UIImage imageNamed:#"NOIMG.png"];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self.contactsTableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"NextView"]) {
//if (!isFiltered) {
ContactDetailsViewController *nextController = [segue destinationViewController];
NSIndexPath *indexPath = [[[self contactsTableView] indexPathsForSelectedRows] objectAtIndex:0];
[nextController setPhoneTypes:[contacts.phoneTypes objectAtIndex:[indexPath row]]];
[nextController setPhoneNumbers:[contacts.phoneNumbers objectAtIndex:[indexPath row]]];
//}
/*else {
ContactDetailsViewController *nextController = [segue destinationViewController];
NSIndexPath *indexPath = [[[self contactsTableView] indexPathsForSelectedRows] objectAtIndex:0];
[nextController setPhoneTypes:[contacts.phoneTypes objectAtIndex:[indexPath row]]];
[nextController setPhoneNumbers:[contacts.phoneNumbers objectAtIndex:[indexPath row]]];
}*/
}
}