UITableView cell rearranging array trouble - ios

i have a UITableView that a user can add and rearrange objects in... when the user moves an item, i try to re-arrange the data array to fit what the user has changed his cell order to... i am obviously not doing it correctly... here is my code
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
NSMutableOrderedSet *temp = [[NSMutableOrderedSet alloc]init];
if(fromIndexPath.row == toIndexPath.row){
temp = _dataArray;
}
int min,max;
if(fromIndexPath.row > toIndexPath.row){min = toIndexPath.row;max = fromIndexPath.row;}
if(fromIndexPath.row < toIndexPath.row){max = toIndexPath.row;min = fromIndexPath.row;}
for(int i = 0; i < _dataArray.count; i++)
{
NSLog(#"%i",i);
if(i == toIndexPath.row)
{
[temp insertObject:_dataArray[fromIndexPath.row] atIndex:i];
}
else
{
if(i >= min && i <= max)
{
if(fromIndexPath.row > toIndexPath.row)
{
[temp insertObject:_dataArray[i] atIndex:i+1];
}
else if(fromIndexPath.row < toIndexPath.row)
{
[temp insertObject:_dataArray[i] atIndex:i-1];
}
}
else
{
[temp insertObject:_dataArray[i] atIndex:i];
}
}
}
NSLog(#"================ Cell Array Testing ================");
for(int i = 0; i < temp.count; i++)
{
NSLog(#"Cell: %#",temp[i]);
}
_dataArray = temp;
}

Related

UICollectionView move items to new section

I'm having serious troubles with the animation of a UICollectionView, similar to the problem mentioned here: UICollectionView crashes when rearranging items between sections
Let's say I have a UICollectionView with 5 different sections, each with 10 cells.
I would like to update the CollectionView with an animation, so the cells will be reordered into 10 sections. No cells with new content will be added nor existing cells removed.
Therefore I'm performing a batch update:
[_resultCollectionView performBatchUpdates:^{
[_resultCollectionView insertSections:insertSections];
[_resultCollectionView deleteSections:deleteSections];
//[_resultCollectionView insertItemsAtIndexPaths:insertIndexPaths];
//[_resultCollectionView deleteItemsAtIndexPaths:deleteIndexPaths];
for (all items which need to be moved...) {
[_resultCollectionView moveItemAtIndexPath:sourcePath toIndexPath:destinationPath];
}
} completion:^(BOOL finished) {
//[_resultCollectionView reloadData];
nil;
}];
If I perform insertSections, deleteSections, insertItemsAtIndexPath, deleteItemsAtIndexPath and reloadData once the block was performed everything works fine which means my dataSource and delegates work properly in theory. Except it's not animated yet ...
If I perform insertSections, deleteSections and moveItemAtIndexPath (which should work since the cells only get rearranged) i get this little bug:
cannot move a row into a newly inserted section (5)
If I perform insertSections, deleteSections and moveItemAtIndexPath but exclude any movement into a newly inserted section I obviously get invalid number of items in the sections.
Does anybody have a solution for this problem?
I followed john1034's link and figured out a quite tricky way to do it. You have to split up the work in three steps:
Adding new sections if necessary. The new sections will be empty first.
Adding, removing and moving cells within the new and existing sections.
Deleting sections if necessary.
For sure there are many lines which can be further improved. Especially the search functions are quite inefficient...
static BOOL addingSections = NO;
static BOOL updatingCollectionView = NO;
static BOOL removingSections = NO;
- (void)reloadResultCollectionView
//IndexUnloadedArray: a link to my CollectionViewData before the update
//IndexArray: a link to my CollectionViewData after the update
//start only if something changed
if (![IndexArray isEqual:IndexUnloadedArray]) {
NSMutableIndexSet *deleteSections = [[NSMutableIndexSet alloc] init];
NSMutableIndexSet *insertSections = [[NSMutableIndexSet alloc] init];
NSMutableArray *deleteIndexPaths = [[NSMutableArray alloc] init];
NSMutableArray *insertIndexPaths = [[NSMutableArray alloc] init];
//step 1 - add collectionView sections
for (int i = 0; i < IndexArray.count; i++) {
if (i >= IndexUnloadedArray.count) {
[insertSections addIndex:i];
}
}
NSLog(#"insert sections:%#", insertSections);
_sectionAmount = (int)_distanceUnloadedArray.count + (int)insertSections.count;
addingSections = YES;
[_resultCollectionView performBatchUpdates:^{
[_resultCollectionView insertSections:insertSections];
} completion:^(BOOL finished) {
nil;
}];
addingSections = NO;
//step 2 - update collectionView
//adding cells if there are not enough
for (int i = 0; i < IndexArray.count; i++) {
for (int j = 0; j < (int)[[IndexArray objectAtIndex:i] count]; j++) {
NSNumber *searchIndex = [[IndexArray objectAtIndex:i] objectAtIndex:j];
bool found = NO;
for (int k = 0; k < IndexUnloadedArray.count; k++) {
if ([[IndexUnloadedArray objectAtIndex:k] containsObject:searchIndex]) {
found = YES;
k = (int)IndexUnloadedArray.count;
}
}
if (!found) {
[insertIndexPaths addObject:[NSIndexPath indexPathForRow:j inSection:i]];
}
}
}
NSLog(#"insert cells:%#", insertIndexPaths);
//deleting cells if there are too many
for (int i = 0; i < IndexUnloadedArray.count; i++) {
if (![deleteSections containsIndex:i]) {
for (int j = 0; j < (int)[[IndexUnloadedArray objectAtIndex:i] count]; j++) {
NSNumber *searchIndex = [[IndexUnloadedArray objectAtIndex:i] objectAtIndex:j];
bool found = NO;
for (int k = 0; k < IndexArray.count; k++) {
if ([[IndexArray objectAtIndex:k] containsObject:searchIndex]) {
found = YES;
k = (int)IndexArray.count;
}
}
if (!found) {
[deleteIndexPaths addObject:[NSIndexPath indexPathForRow:j inSection:i]];
}
}
}
}
NSLog(#"deleting cells:%#", deleteIndexPaths);
updatingCollectionView = YES;
[_resultCollectionView performBatchUpdates:^{
[_resultCollectionView insertItemsAtIndexPaths:insertIndexPaths];
[_resultCollectionView deleteItemsAtIndexPaths:deleteIndexPaths];
for (int i = 0; i < IndexUnloadedArray.count; i++) {
for (int j = 0; j < [[IndexUnloadedArray objectAtIndex:i] count]; j++) {
NSIndexPath *sourcePath = [NSIndexPath indexPathForRow:(j) inSection:i];
NSNumber *searchIndex = [[IndexUnloadedArray objectAtIndex:i] objectAtIndex:j];
NSIndexPath *destinationPath;
for (int k = 0; k < IndexArray.count; k++) {
if ([[IndexArray objectAtIndex:k] containsObject:searchIndex]) {
NSInteger *row = [[IndexArray objectAtIndex:k] indexOfObject:searchIndex];
destinationPath = [NSIndexPath indexPathForItem:row inSection:k];
if (sourcePath != destinationPath) {
NSLog(#"moving cell from %ld.%ld to %ld.%ld (%#)", (long)sourcePath.section, (long)sourcePath.row, (long)destinationPath.section, (long)destinationPath.row);
[_resultCollectionView moveItemAtIndexPath:sourcePath toIndexPath:destinationPath];
} else {
NSLog(#"object %ld.%ld stays in position", (long)sourcePath.section, (long)sourcePath.row);
}
}
}
}
}
} completion:^(BOOL finished) {
nil;
}];
updatingCollectionView = NO;
//step 3 - deleting sections if there are too many
for (int i = 0; i < IndexUnloadedArray.count; i++) {
if (i >= IndexArray.count) {
[deleteSections addIndex:i];
}
}
NSLog(#"delete sections:%#", deleteSections);
_sectionAmount = (int)_distanceArray.count;
removingSections = YES;
[_resultCollectionView performBatchUpdates:^{
[_resultCollectionView deleteSections:deleteSections];
} completion:^(BOOL finished) {
//update table header and footer
[_resultCollectionView reloadData];
}];
removingSections = NO;
}
}
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView
{
return _sectionAmount;
}
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section
{
if (addingSections) {
if (section < _distanceUnloadedArray.count) {
return [[_distanceUnloadedArray objectAtIndex:section] count];
} else {
return 0;
}
}
if (updatingCollectionView) {
if (section < _distanceArray.count) {
return [[_distanceArray objectAtIndex:section] count];
} else {
return 0;
}
}
if (removingSections) {
return [[_distanceArray objectAtIndex:section] count];
}
return [[_distanceArray objectAtIndex:section] count];
}

Unable to figure out the value change of the integer in the code

I have this code and I am trying to understand it. This has an int value 'currentExpandIndex' ,I couldnt figure out why it is changing because I dont find proper initiation of it. The int is first given the value -1,but later in code the int value changes according to the indexpath. I coldnt find the relation between the int and the indexpath declared in the code.Kindly tell me,why
the code is:
#interface AccordionTableViewController : UITableViewController {
NSArray *topItems;
NSMutableArray *subItems; // array of arrays
int currentExpandedIndex;
}
#end
//.m file
- (id)init {
self = [super init];
if (self) {
topItems = [[NSArray alloc] initWithArray:[self topLevelItems]];
subItems = [NSMutableArray new];
currentExpandedIndex = -1;
NSLog(#"currenyt index -init is %d",currentExpandedIndex);
for (int i = 0; i < [topItems count]; i++) {
[subItems addObject:[self subItems]];
}
}
return self;
}
#pragma mark - Data generators
- (NSArray *)topLevelItems {
NSMutableArray *items = [NSMutableArray array];
for (int i = 0; i < NUM_TOP_ITEMS; i++) {
[items addObject:[NSString stringWithFormat:#"Item %d", i + 1]];
}
return items;
}
- (NSArray *)subItems {
NSMutableArray *items = [NSMutableArray array];
int numItems = arc4random() % NUM_SUBITEMS + 2;
for (int i = 0; i < numItems; i++) {
[items addObject:[NSString stringWithFormat:#"SubItem %d", i + 1]];
}
return items;
}
#pragma mark - View management
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"currenyt index -view did load is %d",currentExpandedIndex);
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"currenyt index -no of rows in section is %d",currentExpandedIndex);
return [topItems count] + ((currentExpandedIndex > -1) ? [[subItems objectAtIndex:currentExpandedIndex] count] : 0);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ParentCellIdentifier = #"ParentCell";
static NSString *ChildCellIdentifier = #"ChildCell";
NSLog(#"currenyt index-cell for row at index is %d",currentExpandedIndex);
BOOL isChild =
currentExpandedIndex > -1
&& indexPath.row > currentExpandedIndex
&& indexPath.row <= currentExpandedIndex + [[subItems objectAtIndex:currentExpandedIndex] count];
UITableViewCell *cell;
if (isChild) {
cell = [tableView dequeueReusableCellWithIdentifier:ChildCellIdentifier];
}
else {
cell = [tableView dequeueReusableCellWithIdentifier:ParentCellIdentifier];
}
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ParentCellIdentifier] autorelease];
}
if (isChild) {
cell.detailTextLabel.text = [[subItems objectAtIndex:currentExpandedIndex] objectAtIndex:indexPath.row - currentExpandedIndex - 1];
}
else {
int topIndex = (currentExpandedIndex > -1 && indexPath.row > currentExpandedIndex)
? indexPath.row - [[subItems objectAtIndex:currentExpandedIndex] count]
: indexPath.row;
cell.textLabel.text = [topItems objectAtIndex:topIndex];
cell.detailTextLabel.text = #"";
}
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
BOOL isChild =
currentExpandedIndex > -1
&& indexPath.row > currentExpandedIndex
&& indexPath.row <= currentExpandedIndex + [[subItems objectAtIndex:currentExpandedIndex] count];
if (isChild) {
NSLog(#"A child was tapped, do what you will with it");
NSLog(#"currenyt index -did select is %d",currentExpandedIndex);
return;
}
NSLog(#"currenyt index -did select out is %d",currentExpandedIndex);
[self.tableView beginUpdates];
if (currentExpandedIndex == indexPath.row) {
[self collapseSubItemsAtIndex:currentExpandedIndex];
currentExpandedIndex = -1;
}
else {
BOOL shouldCollapse = currentExpandedIndex > -1;
if (shouldCollapse) {
[self collapseSubItemsAtIndex:currentExpandedIndex];
}
currentExpandedIndex = (shouldCollapse && indexPath.row > currentExpandedIndex) ? indexPath.row - [[subItems objectAtIndex:currentExpandedIndex] count] : indexPath.row;
[self expandItemAtIndex:currentExpandedIndex];
}
[self.tableView endUpdates];
}
- (void)expandItemAtIndex:(int)index {
NSMutableArray *indexPaths = [NSMutableArray new];
NSArray *currentSubItems = [subItems objectAtIndex:index];
int insertPos = index + 1;
for (int i = 0; i < [currentSubItems count]; i++) {
[indexPaths addObject:[NSIndexPath indexPathForRow:insertPos++ inSection:0]];
}
[self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
//[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
[indexPaths release];
}
- (void)collapseSubItemsAtIndex:(int)index {
NSMutableArray *indexPaths = [NSMutableArray new];
for (int i = index + 1; i <= index + [[subItems objectAtIndex:index] count]; i++) {
[indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
[self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
[indexPaths release];
}
In didSelectRowAtIndexPath: you have this line:
currentExpandedIndex =
(shouldCollapse && indexPath.row > currentExpandedIndex) ?
indexPath.row - [[subItems objectAtIndex:currentExpandedIndex] count] :
indexPath.row;
This line assign indexPath.row or indexPath.row - [[subItems objectAtIndex:currentExpandedIndex] count] to currentExpandedIndex.
currentExpandedIndex = (shouldCollapse && indexPath.row > currentExpandedIndex) ? indexPath.row - [[subItems objectAtIndex:currentExpandedIndex] count] : indexPath.row;
On each didSelectRow it will change.
First, set a breakpoint in -init. Depending on how you create this controller, it might not be called, in which case it will be 0. Try -initWithCoder: instead if this is the case. Otherwise, I only see this set in one place: -tableView:didSelectRowAtIndexPath:, where it can be set to the row or indexPath.row - [[subItems objectAtIndex:currentExpandedIndex] count]. Depending on what else you are doing with the table, this might be a good job for sections or expandable individual rows to simplify.

Switch example from UITableViewController to UITableView

I am relatively new in iOS, I have found an example of accordion table view that I need. But the thing is that example is TableViewController and I need to implement TableView inside viewController. Can you please help me. What I have tried to do is create tableView, declare it in the h file as
#property (strong, nonatomic) IBOutlet UITableView *MyTb;
and then change all appearances of self.tableView to self.MyTb but it did not work, oh also changed
AccordionTableViewController : UITableViewController
to
AccordionTableViewController : UIViewController
So here is the original code, please help me and provide some guiadance to it, thanks.
h file:
#import <UIKit/UIKit.h>
#interface AccordionTableViewController : UITableViewController {
NSArray *topItems;
NSMutableArray *subItems; // array of arrays
int currentExpandedIndex;
}
#end
m file:
#import "AccordionTableViewController.h"
#define NUM_TOP_ITEMS 20
#define NUM_SUBITEMS 6
#implementation AccordionTableViewController
- (id)init {
self = [super init];
if (self) {
topItems = [[NSArray alloc] initWithArray:[self topLevelItems]];
subItems = [NSMutableArray new];
currentExpandedIndex = -1;
for (int i = 0; i < [topItems count]; i++) {
[subItems addObject:[self subItems]];
}
}
return self;
}
#pragma mark - Data generators
- (NSArray *)topLevelItems {
NSMutableArray *items = [NSMutableArray array];
for (int i = 0; i < NUM_TOP_ITEMS; i++) {
[items addObject:[NSString stringWithFormat:#"Item %d", i + 1]];
}
return items;
}
- (NSArray *)subItems {
NSMutableArray *items = [NSMutableArray array];
int numItems = arc4random() % NUM_SUBITEMS + 2;
for (int i = 0; i < numItems; i++) {
[items addObject:[NSString stringWithFormat:#"SubItem %d", i + 1]];
}
return items;
}
#pragma mark - View management
- (void)viewDidLoad {
[super viewDidLoad];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [topItems count] + ((currentExpandedIndex > -1) ? [[subItems objectAtIndex:currentExpandedIndex] count] : 0);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ParentCellIdentifier = #"ParentCell";
static NSString *ChildCellIdentifier = #"ChildCell";
BOOL isChild =
currentExpandedIndex > -1
&& indexPath.row > currentExpandedIndex
&& indexPath.row <= currentExpandedIndex + [[subItems objectAtIndex:currentExpandedIndex] count];
UITableViewCell *cell;
if (isChild) {
cell = [tableView dequeueReusableCellWithIdentifier:ChildCellIdentifier];
}
else {
cell = [tableView dequeueReusableCellWithIdentifier:ParentCellIdentifier];
}
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ParentCellIdentifier] autorelease];
}
if (isChild) {
cell.detailTextLabel.text = [[subItems objectAtIndex:currentExpandedIndex] objectAtIndex:indexPath.row - currentExpandedIndex - 1];
}
else {
int topIndex = (currentExpandedIndex > -1 && indexPath.row > currentExpandedIndex)
? indexPath.row - [[subItems objectAtIndex:currentExpandedIndex] count]
: indexPath.row;
cell.textLabel.text = [topItems objectAtIndex:topIndex];
cell.detailTextLabel.text = #"";
}
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
BOOL isChild =
currentExpandedIndex > -1
&& indexPath.row > currentExpandedIndex
&& indexPath.row <= currentExpandedIndex + [[subItems objectAtIndex:currentExpandedIndex] count];
if (isChild) {
NSLog(#"A child was tapped, do what you will with it");
return;
}
[self.tableView beginUpdates];
if (currentExpandedIndex == indexPath.row) {
[self collapseSubItemsAtIndex:currentExpandedIndex];
currentExpandedIndex = -1;
}
else {
BOOL shouldCollapse = currentExpandedIndex > -1;
if (shouldCollapse) {
[self collapseSubItemsAtIndex:currentExpandedIndex];
}
currentExpandedIndex = (shouldCollapse && indexPath.row > currentExpandedIndex) ? indexPath.row - [[subItems objectAtIndex:currentExpandedIndex] count] : indexPath.row;
[self expandItemAtIndex:currentExpandedIndex];
}
[self.tableView endUpdates];
}
- (void)expandItemAtIndex:(int)index
{
NSMutableArray *indexPaths = [NSMutableArray new];
NSArray *currentSubItems = [subItems objectAtIndex:index];
int insertPos = index + 1;
for (int i = 0; i < [currentSubItems count]; i++) {
[indexPaths addObject:[NSIndexPath indexPathForRow:insertPos++ inSection:0]];
}
[self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
//[indexPaths release];
}
- (void)collapseSubItemsAtIndex:(int)index
{
NSMutableArray *indexPaths = [NSMutableArray new];
for (int i = index + 1; i <= index + [[subItems objectAtIndex:index] count]; i++)
{
[indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
[self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
//[indexPaths release];
}
- (void)dealloc
{
[topItems release];
[subItems release];
[super dealloc];
}
#end
You must set your view controller as delegate and datasource of your tableview:
#interface AccordionTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
in your header file and in viewDidLoad:
-(void)viewDidLoad {
[super viewDidLoad];
self.MyTb.delegate = self;
self.MyTb.dataSource = self;
}
Or you can set the datasource and delegate in Storyboard. You must also make sure you have connected the table view to MyTb IBOutlet in storyboard.

Array empty when trying to populate tableview

I'm trying to create a second section which is where section.indexPath = 0. This section is objects which is generated from distance between two locations which is done in the didUpdateToLocation. When trying to populate the tableview with the objects from the array it shows:
index 0 beyond bounds for empty array'
How can i show the nearStoresArray in the tableview without getting the empty array error.
Here is the cellForRowAtIndexPath. Here it gives an error and say that nearStoresArray is empty. I guess thats because the tableview is showing before the didUpdateToLocation.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (indexPath.section == 0) {
indexNo = [nearStoresArray objectAtIndex:indexPath.row];
NSLog(#"%d", [nearStoresArray count]);
} else if (indexPath.section == 1) {
if (tableView == self.searchDisplayController.searchResultsTableView) {
indexNo = [filteredArray objectAtIndex:indexPath.row];
} else {
indexNo = [storesArray objectAtIndex:indexPath.row];
}
}
cell.textLabel.text = [indexNo valueForKey:#"name"];
return cell;
}
Here is the didUpdateToLocation method. This method creates the nearStoresArray, which works fine.
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
[locationManager stopUpdatingLocation];
locationManager = nil;
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
for (int i = 0; i < [storesArray count]; i++) {
CLLocationDegrees latitude = [[[storesArray objectAtIndex:i] valueForKey:#"lat"] doubleValue];
CLLocationDegrees longitude = [[[storesArray objectAtIndex:i] valueForKey:#"long"] doubleValue];
CLLocation *checkPosition = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
CLLocationDistance distance = [checkPosition distanceFromLocation:currentLocation];
float distanceInKm = distance / 1000;
if (distanceInKm < 5) {
[nearStoresArray removeAllObjects];
[nearStoresArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:
[[storesArray objectAtIndex:i] valueForKey:#"id"], #"id",
[[storesArray objectAtIndex:i] valueForKey:#"name"], #"name",
[[storesArray objectAtIndex:i] valueForKey:#"lat"], #"lat",
[[storesArray objectAtIndex:i] valueForKey:#"long"], #"long",
[[storesArray objectAtIndex:i] valueForKey:#"address"], #"address",
[[storesArray objectAtIndex:i] valueForKey:#"zip"], #"zip"
, nil]];
NSLog(#"%#", nearStoresArray);
}
[self.tableView reloadData];
}
}
}
numberOfRows Method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section==0) {
return [nearStoresArray count];
} else if (section==1) {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [filteredArray count];
} else {
return [storesArray count];
}
} else {
return 0;
}
}
You can directly Access Section Like
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0) {
return [nearStoresArray count];
}
else if (section == 1) {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [filteredArray count];
}
else {
return [storesArray count];
}
}
}
I believe you need to update numberOfRowsInSection method, like below -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0) {
return [nearStoresArray count];
}
else if (section == 1) {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [filteredArray count];
}
else {
return [storesArray count];
}
}
else {
return 0;
}
}

How to add one array into 2 sections UITableView

Here is my code:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger numberOfRowsPerSection = 0;
if (section == 0) {
for (int i = 0; i < [[[BNRItemStore sharedStore] allItems] count]; i ++) {
BNRItem *item = [[[BNRItemStore sharedStore] allItems] objectAtIndex:i];
if ([item valueInDollars] > 50) {
numberOfRowsPerSection ++;
}
}
}else{
for (int i = 0; i < [[[BNRItemStore sharedStore] allItems] count]; i ++) {
BNRItem *item = [[[BNRItemStore sharedStore] allItems] objectAtIndex:i];
if ([item valueInDollars] == 73) {
numberOfRowsPerSection ++;
}
}
}
return numberOfRowsPerSection;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell"];
if (!cell) {
cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"UITableViewCell"];
}
BNRItem *p = [[[BNRItemStore sharedStore] allItems] objectAtIndex:[indexPath row]];
if ([p valueInDollars] > 50 && indexPath.section == 0) {
[[cell textLabel] setText:[p description]];
}else if(indexPath.section == 1){
[[cell textLabel] setText:[p description]];
}
return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
I want to display in one section results > 50 and the other section the rest of the result but I don't know how to do it. I am getting duplicate results in each section.
Thanks
Your code doesn't reflect what you're describing ( > 50 and == 73 are kind of intersecting):
if (section == 0) {
for (int i = 0; i < [[[BNRItemStore sharedStore] allItems] count]; i ++) {
...
if ([item valueInDollars] > 50) {
...
}
}
}else{
for (int i = 0; i < [[[BNRItemStore sharedStore] allItems] count]; i ++) {
...
if ([item valueInDollars] == 73) {
...
}
}
}
And this line is incorrect too:
BNRItem *p = [[[BNRItemStore sharedStore] allItems] objectAtIndex:[indexPath row]];
because the indexPath.row will go with an indexPath.section (it means the row is relative to the section, not to the whole table). This is main cause of your problem having the same results for both sections.
Anyway, my suggestion for you is to perform a preprocessing step (maybe in viewDidLoad or somewhere else) to split your array into 2 arrays (one for each section) instead of using only one array for both sections.
If you are using a NSFetchedResultsController you can use the sectionNameKeyPath: argument to specify a "group-by" parameter. In your case you might just create a simple 0/1 property to your objects in the array.
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:_managedObjectContext
sectionNameKeyPath:#"threshold"
cacheName:#"Root"];

Resources