tableView:numberOfRowsInSection: called twice in a row - ios

I'm getting an error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.
because I'm adding an object to one instance of an array, but then reloading the table view from another instance of what is supposed to be the same array. How can I create a single instance of the array and just pass it around from class to class? I can do it easily in java, but in Objective-C you can't make static variables so I'm not sure how to do this.
EDIT: more code.
Here is a method from another class that is called in order to save a file. I'm using Core Data, so first it adds the file to the context (model), then to the array, then it saves the context. This method is in a class called 'Player'
-(BOOL)saveRecording {
Bank *B = [MusikerViewController daBank];
AudioTableViewController *ATVC2 = [MusikerViewController ATVControl];
NSLog(#"Place A");
AudioFile *myAudioFileMusicX314 = [[B addAudioFileEntityToModelWithDate:myDate andURLString:strPath] retain];
NSLog(#"Place B");
myAudioFileMusicX314.type = true;
[ATVC2 addAudioEntityToArray:myAudioFileMusicX314];
NSLog(#"Place C ***********************************************");
if(![B saveContext]) { //save context after adding file to keep consistancy
NSLog(#"addAudioFileEntityToModel is returning a nil managedObjectContext");
return NO;
}
NSLog(#"Place D");
[myDate release];
[strPath release];
[myAudioFileMusicX314 release];
[ATVC2 release];
NSLog(#"Place E");
return YES;
}
The following method is in the class that contains the table view--its caled AudioTableViewController
-(void)addAudioEntityToArray:(AudioFile *)event {
NSIndexPath *indexPath;
if(event.type) {
[[MusikerViewController recordingsArray] addObject:event];//self?
indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
}
else {
[[MusikerViewController downloadsArray] addObject:event];
indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
}
[[self tableView] setEditing:YES animated:NO];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationNone];
}
The following method adds the object to my model
- (AudioFile *)addAudioFileEntityToModelWithDate:(NSDate *)theD andURLString:(NSString *)str {
NSLog(#"addAudio...WithDate -- called");
sound = (AudioFile *)[NSEntityDescription insertNewObjectForEntityForName:#"AudioFile" inManagedObjectContext:managedObjectContext];
sound.creationDate = theD;
sound.soundPath = str; //set the sound path to the sound file's url
[self alertForTitle];
NSLog(#"No problems yet at place D - addaudio...String, sound title is %#", sound.title);
NSLog(#"Context at addAudioFileEntityToModel is: %#", managedObjectContext);
return sound;
}
here is the important parts of MusikViewController.h -- it keeps track of recordingsArray and downloadsArray
#interface MusikerViewController : UIViewController {
}
NSMutableArray *recordingsArray;
NSMutableArray *downloadsArray;
+ (NSMutableArray *)recordingsArray;
+ (NSMutableArray *)downloadsArray;
and MusikViewController.m
+ (NSMutableArray *)recordingsArray {
NSLog(#"recordingsArray called");
if(!recordingsArray) {
recordingsArray = [[NSMutableArray alloc] init];
NSMutableArray *bigTempArray = [[[[Bank alloc] init] autorelease] getFetchArray]; //change this
for(AudioFile *af in bigTempArray)
if(af.type) {
[recordingsArray addObject:af];
}
NSLog(#"recordingsArray exists");
}
return recordingsArray;
}
+ (NSMutableArray *)downloadsArray {
NSLog(#"recordingsArray called");
if(!downloadsArray) {
downloadsArray = [[NSMutableArray alloc] init];
// if(!bigTempArray)
NSMutableArray *bigTempArray = [[[[Bank alloc] init] autorelease] getFetchArray];
for(AudioFile *af in bigTempArray)
if(!af.type) {
[downloadsArray addObject:af];
}
}
return downloadsArray;
}
and some AudioTableViewController methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
NSLog(#"Place F");
if(section == 0) {
return [[MusikerViewController recordingsArray] count];
}
else if (section == 1) {
return [[MusikerViewController downloadsArray] count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
AudioFile *event;
if(indexPath.section == 0) {
event = (AudioFile *)[[MusikerViewController recordingsArray] objectAtIndex:indexPath.row];
} else if (indexPath.section == 1) {
NSLog(#"downAry indexPath caled at cellForRow...Path");
event = (AudioFile *)[[MusikerViewController downloadsArray] objectAtIndex:indexPath.row];
}
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
if(event.title) {
cell.detailTextLabel.text = [Player dateString:event.creationDate];
cell.textLabel.text = event.title;
} else {
cell.textLabel.text = [Player dateString:event.creationDate];
cell.detailTextLabel.text = nil;
}
return cell;
}
- (void)viewDidLoad //viewDidLoad for AudioTableViewController
{
[[self tableView] reloadData];
NSLog(#"viewDidLoad called for AudioTableViewController");
[super viewDidLoad];
self.title = #"Audio Files";//put this in application delegate
// Set up the buttons.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
}

If your data model changes you need to either reload the tableView, or insert/remove the rows otherwise the tableview will freak out on you. It doesn't matter how many times tableView:numberOfRowsInSection is called, your data model can't return a different number without first reloading or updating the tableview.
Based on your logging my guess is that your downloads array is changing quantities. It makes it past the NSLog then dies in _endCellAnimationsWithContext.

Related

How to implement only single cell selection in each section in the tableview in iOS, Objective C

I have a table view with 5 sections and I have set the tableview selection to multiple. Each section have different number of rows. What I want is to set that the user can select only one cell from each section(in my table user can select any number of cells).
ex: 5 cells from 5 sections.
It should be impossible to select more than one cell from any section. If user select another cell from same section, previously selected cell should be deselected. How can I do this. This is a sample implementation of didSelectRowAtIndexPath.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
HoteldetalcelloneTableViewCell *cellone = (HoteldetalcelloneTableViewCell *)[self.detailtableView cellForRowAtIndexPath:indexPath];
HoteldetailcelltwoTableViewCell *celltwo = (HoteldetailcelltwoTableViewCell *)[self.detailtableView cellForRowAtIndexPath:indexPath];
//I have implement for two sections to test.
if(indexPath.section == 0)
{
HotelDetailsone *secone = [roomonearray objectAtIndex:indexPath.row];
HoteldetailsforBooking *book = [HoteldetailsforBooking new];
if([secone.offerallow isEqualToString:#"True"])
{
celltwo.selectedsignLabel.hidden = NO;
}
else
{
cellone.selectedsignLabelone.hidden = NO;
}
// [self.detailtableView reloadData];
NSLog(#"price for room 1 : %#", secone.itempriceText);
}
else
{
HotelDetailsone *sectwo = [roomtwoarray objectAtIndex:indexPath.row];
HoteldetailsforBooking *book = [HoteldetailsforBooking new];
if([sectwo.offerallow isEqualToString:#"True"])
{
celltwo.selectedsignLabel.hidden = NO;
}
else
{
cellone.selectedsignLabelone.hidden = NO;
}
// [self.detailtableView reloadData];
NSLog(#"price for room 1 : %#", sectwo.itempriceText);
}
}
You need to keep track on the selection of cell. So you need to store selected indexpath in array.
in ViewController.h declare property like this
#property(nonatomic,strong) NSMutableDictionary *selectionData;
Now in ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.selectionData=[[NSMutableDictionary alloc]init];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"mycell"];
if ([self.selectionData objectForKey:[NSString stringWithFormat:#"%ld",(long)indexPath.section] ] != nil) {
NSMutableArray *sectionData=[[self.selectionData objectForKey:[NSString stringWithFormat:#"%ld",(long)indexPath.section]] mutableCopy];
if (![sectionData containsObject:[NSNumber numberWithLong:indexPath.row]])
{
cell.accessoryType = UITableViewCellAccessoryNone;
cell.numberlabel.text = #"2";
}
else
{
cell.numberlabel.text = #"***";
cell.accessoryType=UITableViewCellAccessoryCheckmark;
}
}
else
{
cell.numberlabel.text = #"2";
cell.accessoryType = UITableViewCellAccessoryNone;
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"selected section :%li ---> selected row :%li",(long)indexPath.section, (long)indexPath.row);
[self handleSelectionForSection:indexPath.section row:indexPath.row];
[self.tablev reloadData];
}
-(void)handleSelectionForSection:(long)sectionIndex row:(long)rowIndex
{
if ([self.selectionData objectForKey:[NSString stringWithFormat:#"%ld",sectionIndex] ] != nil) {
NSMutableArray *sectionData=[[self.selectionData objectForKey:[NSString stringWithFormat:#"%ld",sectionIndex]] mutableCopy];
if (![sectionData containsObject:[NSNumber numberWithLong:rowIndex]])
{
//removing previous selected rows
[sectionData removeAllObjects];
[sectionData addObject:[NSNumber numberWithLong:rowIndex]];
[self.selectionData setObject:sectionData forKey:[NSString stringWithFormat:#"%ld",sectionIndex]];
}
else
{
//cell you tapped is already selected,
// you can deselect it by removing object
//if you dont want to deselect it comment following lines
[sectionData removeObject:[NSNumber numberWithLong:rowIndex]];
[self.selectionData setObject:sectionData forKey:[NSString stringWithFormat:#"%ld",sectionIndex]];
}
}
else
{
//section key not available so we need to create it
NSMutableArray *sectionData=[[NSMutableArray alloc]init];
[sectionData addObject:[NSNumber numberWithLong:rowIndex]];
[self.selectionData setObject:sectionData forKey:[NSString stringWithFormat:#"%ld",sectionIndex]];
}
NSLog(#"All Selection : %#",self.selectionData);
}
Your numberOfRowsInSection, numberOfSectionsInTableView and titleForHeaderInSection will remain same.
Let me know if you have any query.
You can set selection property of tableview from interface builder. Select your tableview in IB and then select attribute inspector and setsingle selectiontoselection` property like below screenshot.
Or you can set programattically,
self.tableView.allowsMultipleSelection = NO;
Update :
If you want single selection per section then you can implement willSelectRowAtIndexPath as below,
- (NSIndexPath*)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath*)indexPath {
for ( NSIndexPath* selectedIndexPath in tableView.indexPathsForSelectedRows ) {
if ( selectedIndexPath.section == indexPath.section )
[tableView deselectRowAtIndexPath:selectedIndexPath animated:NO] ;
}
return indexPath ;
}
In this case you should allow multiple selection in tableview i think.
Reference : Answer of John Sauer
Looks like you are updating celltwo / cellone selectedsignLabel.hidden on table selection. so #Lion solution will not working. You have to save the last selected index using below code :
#property (nonatomic, strong) NSMutableDictionary *selectedIndexPathDict;
// in viewDidLoad:
self.tableView.allowsMultipleSelection = YES;
self.selectedIndexPathDict = [[NSMutableDictionary alloc] init];
//In table view delegate.
- (NSIndexPath*)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath*)indexPath {
NSString *indexSection = [NSString stringWithFormat:#"%ld", (long)indexPath.section];
NSIndexPath *indexPath1 = self.selectedIndexPathDict[indexSection];
if ( indexPath1) {
HotelDetailsone *secone = [roomonearray objectAtIndex:indexPath.row];
secone.offerallow ^= YES; //toggle bool value
// update new selected index path.
[self.selectedIndexPathDict setObject:indexPath forKey:indexSection];
//reload previous selected cell.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
[tableView beginUpdates];
[tableView reloadRowsAtIndexPaths:#[indexPath1] withRowAnimation:UITableViewRowAnimationFade];
[tableView endUpdates];
});
} else {
//initialise selected index path
self.selectedIndexPathDict[indexSection] = indexPath;
}
[tableView deselectRowAtIndexPath:indexPath animated:NO] ;
return indexPath ;
}
I have not update the complete working code. But this is the way to achieve. You can also use the userdefault instead of self.selectedIndexPathDict.

UItableView load data on scroll in ios

Hi in my array there is huge amount of data and I have to display it in UITableView. But the condition here is I have to display only 5 records initially,then once the user scroll down I have to load more records.I tried searching it but didn't get any useful answer please help me and I agree that we have to use ((void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath )
Another way
we can adjust the return value of tableView:numberOfRowsInSection: method, every time we want to insert ten rows, you can plus 5 to the return value.
but i am not understand how to do this please help me
my code:
#import "TableViewController.h"
#interface TableViewController ()
{
UITableView * tableView;
NSUInteger reloads_;
NSMutableArray * MainArray;
int scrollValue;
long dataLimit;
NSArray * yourDataSource;
}
#end
#implementation TableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
MainArray = [[NSMutableArray alloc]initWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"7",#"8",#"9",#"10",nil];
tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
tableView.delegate = self;
tableView.dataSource = self;
tableView.backgroundColor = [UIColor clearColor];
[self.view addSubview:tableView];
}
#pragma mark - UITableViewDataSource
// number of section(s), now I assume there is only 1 section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView
{
return 1;
}
// number of row in the section, I assume there is only 1 row
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
return yourDataSource.count;
}
// the cell will be returned to the tableView
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"newFriendCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [yourDataSource objectAtIndex:indexPath.row];
return cell;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
[self estimatedTotalData];
}
- (void)estimatedTotalData
{
long currentRow = ((NSIndexPath *)[[tableView indexPathsForVisibleRows] lastObject]).row;
// 25 here is the initial data count
long estimateDataCount = 25;
while (currentRow > estimateDataCount)
{
estimateDataCount+=25;
}
dataLimit = estimateDataCount;
if (dataLimit == currentRow+1)
{
dataLimit+=25;
if (dataLimit != estimateDataCount)
{
//[self requestForData]; or load necessary data
// take not that dataLimit is the total data that must be displayed.
NSArray *yourLocalData = #[#"1", #"2", #"3", #"4", #"5"];
// just add more sample objects
yourDataSource = [self setsLimitForObject: yourLocalData limit: dataLimit];
[tableView reloadData];
}
}
}
- (NSArray *)setsLimitForObject:(id)object limit:(long)limit
{
if ([object isKindOfClass:[NSArray class]])
{
NSMutableArray *tempArray = [object mutableCopy];
NSRange range = NSMakeRange(0, limit);
if (tempArray.count >= range.length)
return [tempArray subarrayWithRange:range];
else
{
NSLog(#"Out of bounds");
return object;
}
} else NSLog(#"Sets Log: Cannot set limit for object %#", [object class]);
return nil;
}
#end
Try this approach, this is more like a paging...
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self estimatedTotalData];
}
- (void)estimatedTotalData
{
long currentRow = ((NSIndexPath *)[[YourTableView indexPathsForVisibleRows] lastObject]).row;
// 25 here is the initial data count
long estimateDataCount = 25;
while (currentRow > estimateDataCount)
{
estimateDataCount+=25;
}
dataLimit = estimateDataCount;
if (dataLimit == currentRow+1)
{
dataLimit+=25;
if (dataLimit != estimateDataCount)
{
//[self requestForData]; or load necessary data
// take not that dataLimit is the total data that must be displayed.
NSArray *yourLocalData = #[#"1", #"2", #"3", #"4", #"5"];
// just add more sample objects
yourDataSource = [self setsLimitForObject: yourLocalData limit: dataLimit];
[yourTable reloadData];
}
}
}
Update:
- (NSArray *)setsLimitForObject:(id)object limit:(long)limit
{
if ([object isKindOfClass:[NSArray class]])
{
NSMutableArray *tempArray = [object mutableCopy];
NSRange range = NSMakeRange(0, limit);
if (tempArray.count >= range.length)
return [tempArray subarrayWithRange:range];
else
{
NSLog(#"Out of bounds");
return object;
}
} else NSLog(#"Sets Log: Cannot set limit for object %#", [object class]);
return nil;
}
You can use below code for your cellForRowAtIndexPath,
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"newFriendCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [mainArray objectAtIndex:indexPath.row];
if (indexPath.row % 5 == 0) { // this if loop will get execute at every fifth row
// if you are loading data from API response then call API here and add next set of data into your existing array.
// then just reload your tableview by it's name e.g. [theTableView reloadData];
}
return cell;
}
and for your numberOfRowsInSection, instead of fixed 5 rows, just use mainArray.count like below,
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
return mainArray.count;
}

A method being called from another class doesn't return the value it is supposed to in iOS (MVC)

I have implemented MVC in my project. In Model I have a class DBHandler containing below method which is suppose to return me names of saved items
- (NSMutableArray *) displayAllItems
{
NSString* selectAllResume = [NSString stringWithFormat:#"select * from Items"];
sqlite3_stmt* selectStatement = (sqlite3_stmt *)[self getStatement:selectAllResume];
while(sqlite3_step(selectStatement) == SQLITE_ROW)
{
#try {
ResumeDC *resume = [[ResumeDC alloc] init];
NSString *result_output = #"";
int numberOfCoulmns = 1;
for (int a=0; a<numberOfCoulmns; a++)
{
resume.resumeName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectStatement, a)];
NSString *formatout = [NSString stringWithFormat:#"%#", resume.resumeName];
result_output = [result_output stringByAppendingString: formatout];
}
[dataList addObject:result_output]; // the value in the datalist is empty later on.
}
#catch (NSException *exception) {
NSLog(#"We were unable to find the files.");
}
return dataList;
}
}
In View, I have a class SavedItems. Here in viewDidLoad() I am trying to access all the data being read by the above method and get it displayed in the tableview.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.tvMine.delegate = self;
self.tvMine.dataSource = self;
GET_DBHANDLER
[dbHandler displayAllItems];
mydataList = dbHandler.dataList;
numberOfRows = [mydataList count];
[tvMine reloadData];
}
And thats how I am getting it displayed in the table (Just providing it, else the below code is perfect).
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MyIdentifier"];
}
if ([mydataList count] > 0) {
cell.textLabel.text = [mydataList objectAtIndex:indexPath.row];
}
return cell;
}
But I get nothing in return from the displayAllItems when it is being called outside it's class.
The answer should have been what was being asked. I asked people about the method calling and didn't get a single answer. Well the mistake in my code was of method calling as already mentioned by me. Below is the code of doing it the right way
mydataList= [dbHandler displayAllResumes]; // mydataList is an NSMutableArray.
numberOfRows = [mydataList count];
[tvMine reloadData];
Now everything is working perfectly. Thanks for Your Help :/

iOS search bar not showing results

*Update: This actually works, the style for my custom cell hasn't come across and so the cell looks blank. How then do I get the searchResultsTableView to use my custom cell?
I have implemented a search bar in my table view. Searching, filtering all work when I debug, but when I enter characters into the search bar, the results do not load or show. This is everything I'm doing:
#interface InviteTableViewController ()<UIAlertViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate>
#property(nonatomic, strong) NSNumber *contactsCount;
#property(nonatomic, strong) InviteTableViewCell *selectedCell;
#property(strong, nonatomic) NSMutableArray *filteredContactArray;
#property (weak, nonatomic) IBOutlet UISearchBar *contactsSearchBar;
#end
#implementation InviteTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void) extractAllContacts: (ABAddressBookRef) addressBookRef{
NSMutableArray *contactsArray = [NSMutableArray array];
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBookRef);
CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBookRef);
for(int i = 0; i < numberOfPeople; i++){
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
if(firstName){
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
for (CFIndex i = 0; i < ABMultiValueGetCount(emails); i++) {
NSString *email = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(emails, i);
MyUser *amUser = [[MyUser alloc] init];
amUser.email =email;
NSString *fullName =[NSString stringWithFormat:#"%# %#",firstName, (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty))];
amUser.fullName = fullName;
[contactsArray addObject:amUser];
}
}
}
NSLog(#"================================count ============= %d", [contactsArray count]);
contactsArray = [contactsArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSDate *first = [(MyUser*) a fullName];
NSDate *second = [(MyUser*)b fullName];
return [first compare:second];
}];
self.inviteContactsArray = contactsArray;
self.filteredContactArray = [NSMutableArray arrayWithCapacity:[contactsArray count]];
[self.tableView reloadData];
}
- (void)viewDidLoad
{
[super viewDidLoad];
_contactsCount = [NSNumber numberWithInt:0];
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
if (granted) {
[self extractAllContacts: addressBookRef];
[self.tableView reloadData];
} else {
NSString *message = [NSString stringWithFormat:#"You have not given permission to use your address book. Please allow in settings "];
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Enable Contacts" message:message delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
// The user has previously given access, add the contact
[self extractAllContacts:addressBookRef];
}
else {
// The user has previously denied access
// Send an alert telling user to change privacy setting in settings app
}
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [self.filteredContactArray count];
} else {
return [self.inviteContactsArray count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"InviteCell";
InviteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if ( cell == nil ) {
cell = [[InviteTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
MyUser *person = nil;
if (tableView == self.searchDisplayController.searchResultsTableView)
{
person = [self.filteredContactArray objectAtIndex:[indexPath row]];
NSMutableArray *tempArray = self.filteredContactArray;
}
else
{
person = [self.inviteContactsArray objectAtIndex:[indexPath row]];
}
//InviteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
person = [self.inviteContactsArray objectAtIndex:indexPath.row];
cell.nameLabel.text = person.fullName;
cell.emailLabel.text = person.email;
return cell;
}
#pragma mark Content Filtering
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
// Update the filtered array based on the search text and scope.
// Remove all objects from the filtered search array
[self.filteredContactArray removeAllObjects];
// Filter the array using NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.fullName contains[c] %#",searchText];
self.filteredContactArray = [NSMutableArray arrayWithArray:[self.inviteContactsArray filteredArrayUsingPredicate:predicate]];
}
#pragma mark - UISearchDisplayController Delegate Methods
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
#end
This is what it looks like:
Agree with #rdelmar.
BUT There is a kind of tricky behavior in TableView, if you change the code in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
....
InviteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
....
}
to
InviteTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if added the prefix "self." your code should works fine.
and
if ( cell == nil )
{
cell = [[InviteTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
is unnecessary. it will just create a standard "Subtitle Cell" for you that seems not you want, just remove them.
If you want to use the same cell for your main table and the search results table, you should make the cell in a xib (or you could do it entirely in code). In viewDidLoad, register the nib for both table views,
- (void)viewDidLoad {
[super viewDidLoad];
[self.searchDisplayController.searchResultsTableView registerNib:[UINib nibWithNibName:#"InviteTableViewCell" bundle:nil] forCellReuseIdentifier:#"InviteCell"];
[self.tableView registerNib:[UINib nibWithNibName:#"InviteTableViewCell" bundle:nil] forCellReuseIdentifier:#"inviteCell"];
}
In cellForRowAtIndexPath, you can do something like this,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
InviteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"InviteCell" forIndexPath:indexPath];
MyUser *person = ([tableView isEqual:self.tableView])? self.inviteContactsArray[indexPath.row] : self.filteredContactArray[indexPath row];
cell.nameLabel.text = person.fullName;
cell.emailLabel.text = person.email;
return cell;
}
If you've already setup your cell in the storyboard, you can copy and paste it into an empty xib file, so you don't have to set it up all over again. You can delete the cell from your storyboard table view since you will be getting the cell from the xib file instead.
Below line in viewdidload should do the trick
self.searchDisplayController.searchResultsTableView.rowHeight = self.tableView.rowHeight

UIsearch bar not returning data to table

Edited code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil)
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
if (isFiltered) {
int rowCount=indexPath.row;
Aves *filtrada=[filteredTableData objectAtIndex:rowCount];
cell.textLabel.text=filtrada.name;
NSLog(#"mostrando: ");
}else {
int rowCounter=indexPath.row;
Aves *author=[theauthors objectAtIndex:rowCounter];
cell.textLabel.text=author.name;
}
NSLog(#"mostrando: ");
return cell;
}
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
isFiltered = true;
int i;
[filteredTableData removeAllObjects];
for(i=0;[theauthors count]>i;i++)
{
Aves *name=[theauthors objectAtIndex:i];
//NSLog(name.name);
NSRange nameRange = [[name.name lowercaseString] rangeOfString:[text lowercaseString]];
if(nameRange.length>0)
{
[filteredTableData addObject:name];
NSLog(name.name);
}
}
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
}
}
Edit: After working on it a while I solved some problems.Just updated my code, the problem is the repaint of the tableView, every thing else go ok. Check it and give any ideas you have plz ^^
Thx again for your time.
I assume you're using prototype cells? I just had a similar problem in one of my projects.
When search results are displayed and tableView:cellForRowAtIndexPath: is called, the table view passed in the the table belonging to the search results controller, not your main table view. Problem with that is, the search results table view doesn't know anything about your table's prototype cells, so dequeueReusableCellWithIdentifier: returns nil. But just alloc/init'ing a UITableCellView won't give you one of your prototype cells, so whatever UI you laid out in your storyboard isn't there.
The fix is easy: in tableView:cellForRowAtIndexPath:, don't call dequeueReusableCellWithIdentifier: on the tableview passed in; just call it on your main table view. So basically, just change this:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil)
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
to this:
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
There's no need for the nil check; Apple's Storyboards Release Notes says:
The dequeueReusableCellWithIdentifier: method is guaranteed to return
a cell (provided that you have defined a cell with the given
identifier). Thus there is no need to use the “check the return value
of the method” pattern as was the case in the previous typical
implementation of tableView:cellForRowAtIndexPath:.
does your app hits this code if(nameRange.location ==0) ?
Change the code piece of
else
{
isFiltered = true;
int i=0;
[filteredTableData removeAllObjects];
filteredTableData = [[NSMutableArray alloc] init];
//for (Aves* name in theauthors)
for(i=0;[theauthors count]>i;i++)
{
Aves *name=[theauthors objectAtIndex:i];
NSRange nameRange = [name.foodName rangeOfString:text ];
if(nameRange.location ==0)
{
[filteredTableData addObject:name];
}
[self.tableView reloadData];
}
}
to
else
{
isFiltered = true;
int i=0;
[filteredTableData removeAllObjects];
//filteredTableData = [[NSMutableArray alloc] init]; not needed
//for (Aves* name in theauthors)
for(i=0;[theauthors count]>i;i++)
{
Aves *name=[theauthors objectAtIndex:i];
NSRange nameRange = [name.foodName rangeOfString:text ];
if(nameRange.location != NSNotFound)
{
[filteredTableData addObject:name];
}
}
[self.tableView reloadData];
}
use this:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//If the requesting table view is the search display controller's table view, return the count of the filtered list, otherwise return the count of the main list.
if (isFiltered)
{
return [filteredTableData count];
}
else
{
return [theauthors count];
}
}
Replace method:
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
isFiltered = true;
int i=0;
[filteredTableData removeAllObjects];
filteredTableData = [[NSMutableArray alloc] init];
//for (Aves* name in theauthors)
for(i=0;[theauthors count]>i;i++)
{
Aves *name=[theauthors objectAtIndex:i];
NSRange nameRange = [[name.foodName lowercaseString] rangeOfString:[text lowercaseString]];
if(nameRange.length>0)
{
[filteredTableData addObject:name];
[self.tableView reloadData];
}
}
}
}
finally fixed it. Here is my working code, thx you all =)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
if (isFiltered==TRUE) {
int rowCount=indexPath.row;
//for (rowCount=0; rowCount<[filteredTableData count]; rowCount++) {
Aves *filtrada=[filteredTableData objectAtIndex:rowCount];
cell.textLabel.text=filtrada.name;
//}
}else if(isFiltered==FALSE)
{
int rowCounter=indexPath.row;
Aves *author=[theauthors objectAtIndex:rowCounter];
cell.textLabel.text=author.name;
}
return cell;
}
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text {
[filteredTableData removeAllObjects];
filteredTableData=[[NSMutableArray alloc]init ];
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
isFiltered = TRUE;
int i;
for(i=0;[theauthors count]>i;i++)
{
Aves * filtrado=[[Aves alloc]init];
filtrado=[theauthors objectAtIndex:i];
//NSLog(filtrado.name);
NSRange nameRange = [[filtrado.name lowercaseString] rangeOfString:[text lowercaseString]];
if(nameRange.length>0)
{
[filteredTableData addObject:filtrado];
}
}
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil
waitUntilDone:NO];
}
}
You probably want to replace
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
with in your cellForRowAtIndexPath
UITableViewCell *cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
The reason because you're not getting use of the dequeued cell anyway.

Resources