2013-12-08 7 views
4

ближайшие к вам из команды МаркоUITableView клетки странно исчезающие

Мы havign невероятно странная проблема, в которой с нашей точки зрения таблицы клетки, которые обычно появляются примерно так:

enter image description here

Появляются как например:

enter image description here

по результатам обзора, ошибка, кажется, происходит, когда вы р отключите iPhone, затем снова откройте приложение и перейдите в uiviewcontroller, в котором размещен стол. Как-то это делает так, что cellForRowAtIndexPath больше не вызывается, хотя делегат и источники данных все еще настроены на себя. Наши разделы и номера строк по-прежнему являются нормальными, и мы можем прокручивать вниз по таблице. Но поскольку cellForRowAtIndexPath не вызывается, таблицы viewview скрыты.

enter image description here

Вот наша установка TableView (я вынул вещи из этого огромного файла, который не имеет ничего общего с Tableview:

// 
// SPHomeViewController.m 
// Spek 

@interface SPHomeViewController() <UITableViewDataSource, UITableViewDelegate, MKMapViewDelegate, SPCreationViewDelegate, UIAlertViewDelegate, CLLocationManagerDelegate> 
@property (nonatomic, strong) UITableView* tableView; 
@property (nonatomic, strong) NSMutableArray* tableDatasource; 
@property (nonatomic, strong) NSMutableArray* datasource; 
@property (nonatomic, strong) NSMutableArray* friendsDatasource; 
@property (nonatomic, strong) UISegmentedControl* userFilterSegment; 
@property (nonatomic) BOOL isLoadingData; 
@end 

@implementation SPHomeViewController 

@synthesize datasource = _datasource; 
@synthesize friendsDatasource = _friendsDatasource; 
@synthesize tableDatasource = _tableDatasource; 



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 
} 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    //[[SPLocationManager locationManager] startUpdatingLocationForSig]; 
    [self setNeedsStatusBarAppearanceUpdate]; 
    self.view.backgroundColor = [UIColor colorWithRed:230.0f/255.0f green:230.0f/255.0f blue:230.0f/255.0f alpha:1.0]; 
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - kTopBarHeight)]; 
    self.tableView.separatorColor = [UIColor clearColor]; 
    self.tableView.backgroundColor = [UIColor clearColor]; 
    self.tableView.delegate = self; 
    self.tableView.dataSource = self; 
    [self.view addSubview:self.tableView]; 


} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 

    if (self.creationView.center.y > self.view.frame.size.height) { 
     self.creationView = nil; 
    } 
    NSLog(@"Mem warning"); 
} 


//**************************************** 
//**************************************** 
#pragma mark - UITableViewDelegate/DataSource 
//**************************************** 
//**************************************** 

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSLog(@"INDEX PATH ROW: %d AND SECTION: %d", indexPath.row, indexPath.section); 
    if (indexPath.section == 0) { 
     UITableViewCell* cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SPMapCellSpace"]; 
     cell.backgroundColor = [UIColor clearColor]; 
     cell.backgroundView = [[UIView alloc] init]; 
     cell.selectedBackgroundView = [[UIView alloc] init]; 
     return cell; 
    } else if (indexPath.section == self.tableDatasource.count + 1) { 
     UITableViewCell* cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SPBottomCellSpace"]; 
     cell.backgroundColor = [UIColor clearColor]; 
     cell.backgroundView = [[UIView alloc] init]; 
     cell.selectedBackgroundView = [[UIView alloc] init]; 

     return cell; 
    } 
    SPMark* mark = self.tableDatasource[indexPath.section - 1]; 
    NSString* reuseId = [SPHomeViewController cellIdentifierFromData:mark]; 
    SPTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuseId]; 
    if (cell == nil) { 
     cell = [SPTableViewCell cellFromMark:mark reuseID:reuseId]; 
     [cell updateView:YES]; 
    } 
    [cell addDataToCell:mark]; 
    if (indexPath.section >= self.tableDatasource.count - 2 && !self.isLoadingData && self.pageNumber != -1) { 
     self.fetchNextPage = YES; // When the scrollview stops it will load more data if available. 
    } 

    return cell; 
} 

- (unsigned int)getPageNumber { 
    return (self.userFilterSegment.selectedSegmentIndex == 0) ? self.pageNumber : self.friendsPageNumber; 
} 

- (void)setCurrentPageNumber:(unsigned int)page { 
    if (self.userFilterSegment.selectedSegmentIndex == 0) { 
     self.pageNumber = page; 
    } else { 
     self.friendsPageNumber = page; 
    } 
} 

- (void)incrementCurrentPageNumber { 
    if (self.userFilterSegment.selectedSegmentIndex == 0) { 
     self.pageNumber++; 
    } else { 
     self.friendsPageNumber++; 
    } 
} 

// Every cell has a section header so this should be equal to the number of speks returned from the server 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    NSLog(@"section count is: %d",self.tableDatasource.count + 2); 
    return self.tableDatasource.count + 2; // Add two because the mapview needs to go on the top and extra spacing at the bottom. 
} 

// There is a section for every cell, so there is only one cell per section 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return 1; 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (indexPath.section == 0) { 
     return kMapHeight+2; 
    } else if (indexPath.section == self.tableDatasource.count + 1) { 
     return kExtraSpaceBelowHomeView; 
    } 
    SPMark* mark = self.tableDatasource[indexPath.section - 1]; 
    return [SPTableViewCell cellHeightForMark:mark]; 
} 

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (indexPath.section == 0 || indexPath.section == self.tableDatasource.count + 1) { 
     cell.backgroundColor = [UIColor clearColor]; 
    } 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (indexPath.section == 0 || indexPath.section == self.tableDatasource.count + 1) 
     return; 
    SPMark* mark = self.datasource[indexPath.section - 1 ]; 
    SPMarkViewController* markVC = [SPMarkViewController withMark:mark]; 
    [markVC displayData]; 
    [self.navigationController pushViewController:markVC animated:YES]; 
} 

-(void)reloadTableview { 
    [self.tableView setDelegate:self]; 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self.tableView reloadData]; 
     [self.tableView setNeedsDisplay]; 
    }); 
} 

- (void)showNoItems { 
    if (self.tableDatasource.count == 0 && self.accuracyBad == NO) { 
     self.opaqueIcon.hidden = NO; 
     self.noItems.hidden = NO; 
     self.beTheFirst.hidden = NO; 
     self.downArrow.hidden = NO; 
     self.noItemsBackround.hidden = NO; 
     [self.view bringSubviewToFront:self.noItemsBackround]; 
     [self.view bringSubviewToFront:self.downArrow]; 
     [self.view bringSubviewToFront:self.beTheFirst]; 
     [self.view bringSubviewToFront:self.noItems]; 
     [self.view bringSubviewToFront:self.opaqueIcon]; 

    } 
} 

- (void)showTableView { 
    if (self.tableDatasource.count != 0) { 
     self.noItems.hidden = YES; 
     self.beTheFirst.hidden = YES; 
     self.downArrow.hidden = YES; 
     self.noItemsBackround.hidden = YES; 
     self.opaqueIcon.hidden = YES; 

     [self.view sendSubviewToBack:self.noItemsBackround]; 
     [self.view sendSubviewToBack:self.downArrow]; 
     [self.view sendSubviewToBack:self.beTheFirst]; 
     [self.view sendSubviewToBack:self.noItems]; 
     [self.view sendSubviewToBack:self.opaqueIcon]; 
    } 
} 

//**************************************** 
//**************************************** 
#pragma mark - Setters/Getters 
//**************************************** 
//**************************************** 

- (NSMutableArray*)datasource { 
    if (!_datasource) { 
     _datasource = [NSMutableArray array]; 
     if (!self.firstLoad) { 
      [self loadDataForPagination:NO]; 
     } 
    } 
    return _datasource; 
} 

- (NSMutableArray*)friendsDatasource { 
    if (!_friendsDatasource) { 
     _friendsDatasource = [NSMutableArray array]; 
     if (!self.firstLoad) { 
      [self loadDataForPagination:NO]; 
     } 
    } 
    return _friendsDatasource; 
} 

- (NSMutableArray*)tableDatasource { 
    if (!_tableDatasource) { 
     _tableDatasource = (self.userFilterSegment.selectedSegmentIndex == 0) ? self.datasource : self.friendsDatasource; 
    } 
    return _tableDatasource; 
} 

- (SPCreationView*)creationView { 
    if (!_creationView) { 
     UIView* window = [SPUtils getAppDelegate].window; 
     CGSize viewSize = window.frame.size; 
     CGRect startFrame = CGRectMake(0, viewSize.height, [SPUtils screenWidth], [SPUtils screenHeight]); 
     _creationView = [SPCreationView creationView:startFrame delegate:self]; 
     [window insertSubview:_creationView belowSubview:self.creationButton]; 
     _creationView.frame = startFrame; 
    } 
    return _creationView; 
} 

- (void)setTableDatasource:(NSMutableArray *)tableDatasource { 
    _tableDatasource = tableDatasource; 
    [self preFetchImages]; 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     if(_tableDatasource == nil || _tableDatasource.count == 0) { 
      [self showNoItems]; 
     } else { 
      [self showTableView]; 
     } 
     [self reloadTableview]; 
    }); 
} 

- (void)setDatasource:(NSMutableArray *)datasource { 
    _datasource = datasource; 
} 

- (void)setFriendsDatasource:(NSMutableArray *)friendsDatasource { 
    _friendsDatasource = friendsDatasource; 
} 


@end 

Наконец, если вы думаете, что что-то делать с наш делегат, мы не прикасаемся к контроллеру просмотра, поэтому я не вижу, как это может быть проблемой. Может быть, проблема с памятью или проблема с фоновым потоком?

+0

Что вы подразумеваете под «push to this view без нашего контроллера точки зрения»? – rdelmar

+0

Я видел, как такое поведение происходит, если исключение поймано. Есть ли у вас какие-либо блоки @ try/@ catch в любом из методов, вызванных вашим источником данных tableview? Попробуйте воспроизвести эту проблему с включенной контрольной точкой исключения и проверьте, не срабатывает ли она прямо перед исчезновением ячеек. –

+0

Аарон, мы этого не делаем. Но теперь я понимаю, что cellForRowAtIndexPath не вызывается, когда проблема существует. Любая идея, как это могло случиться? – evenodd

ответ

1

Проблема была слишком много фоновых потоков, происходящих сразу. Когда мы перестали пытаться выполнить предварительную выборку изображений, проблема исчезла.

1

Это очень много кода, и возможно, проблема может быть в вашем обычном SPTableViewCell класс и даже не в том, что вы предоставили.

Чтобы ускорить процесс, при воспроизведении проблемы перейдите в отладчик и дамп иерархии представлений. Вы можете сделать это, вызвав [self.view recursiveDescription] на свой контроллер. Это приведет к тому, что вся иерархия подчиненных объектов будет напечатана на консоли, что позволит вам увидеть, что происходит с вашими ячейками, которые должны - но не отображаться. Выводите вывод здесь, если это не дает вам никакой радости.

Но, что еще страннее, что TableView все еще там, и это не проблема подтаблицы, потому что вы все еще можете прокручивать:

Это вполне может еще быть проблемой подтаблицы - TableView получает высота ячеек от отдельного вызова, так что независимо от самих ячеек. Попробуйте распечатать иерархию, чтобы узнать, что происходит.

+0

У вас это есть, все ячейки таблицы выглядят скрытыми.Очень странно, я не могу найти, где мы делаем это где угодно в нашем коде. – evenodd

+0

Вот вставка bin http://pastebin.com/F14q31SE – evenodd

+0

Хм, просто назвал ее, когда ячейка таблицы не была скрыта, но она все еще говорит Hidden = YES – evenodd

Смежные вопросы