ReloadData (UITableView) не работает

У меня большая проблема.

[self.tableView reloadData];

Не работает, и я не понимаю, почему.

[[self tableView] reloadData];

Тоже не работает.

Вот мой код:

.h

@interface ArticleViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate> 
{ 
} 
@end

.m

- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.dataSource = self;
self.tableView.delegate = self;
}

btnLeft = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btnLeft"]
                                         style:UIBarButtonItemStylePlain
                                        target:self
                                        action:@selector(loadPlist)];
self.navigationItem.leftBarButtonItem = btnLeft;

В методе loadPlist я пишу в файле .plist. Эта часть работает нормально.

Как только все будет записано в файл .plist:

btnRight = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btnRight"]
                                          style:UIBarButtonItemStylePlain
                                         target:self
                                         action:@selector(reloadTheTB)];
self.navigationItem.rightBarButtonItem = btnRight;

- (void)reloadTheTB {
NSLog(@"Test reloadTheTB");

[[self tableView] reloadData];
}

Если я коснусь btnRight, я увижу в журнале "Test reloadTheTB".

Вот tableView:cellForRowAtIndexPath:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

        if(cell == nil)
            cell = [self getCellContentView:CellIdentifier];

        contentDictio = [dict objectAtIndex:indexPath.row];

        UILabel *lblTemp1 = (UILabel *)[cell viewWithTag:1];

        lblTemp1.text = [contentDictio objectForKey:@"title"];

        if(indexPath.row % 2) {
            UIView* myBackgroundView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
            myBackgroundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"cell_grise"]];
            cell.backgroundView = myBackgroundView;
        }
        else {
            UIView* myBackgroundView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
            myBackgroundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"cell_blanche"]];
            cell.backgroundView = myBackgroundView;
        }
    }

    return cell;
}

ОБНОВЛЕНИЕ:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dict count];
}

Помоги мне, пожалуйста...


person user1269586    schedule 30.10.2012    source источник
comment
где вы создали tableview????   -  person Venk    schedule 30.10.2012
comment
Итак, какие изменения вы делаете, которые не отражены [tableView reloadData]   -  person mayuur    schedule 30.10.2012
comment
Это UITableViewController, поэтому мне не нужно создавать tableView   -  person user1269586    schedule 30.10.2012
comment
Изменения представляют собой записи новостей в файле plist.   -  person user1269586    schedule 30.10.2012
comment
где методы делегирования для строки и разделов????   -  person Venk    schedule 30.10.2012
comment
Можете ли вы показать нам tableView:cellForRowAtIndexPath:? Похоже, что происходит то, что модель, из которой вы получаете данные в tableView:cellForRowAtIndexPath: для заполнения ячеек, не обновляется путем записи файла .plist или чего-то еще, что вы делаете.   -  person diederikh    schedule 30.10.2012
comment
@DiederikHoogenboom Я обновил свой пост ;-)   -  person user1269586    schedule 30.10.2012
comment
на самом деле будет интереснее посмотреть, как вы обновляете свои источники данных. можете ли вы вставить код своих методов делегатов (numberOfRowsInsection и numberOfSectionsInTableview).   -  person oiledCode    schedule 30.10.2012
comment
Вы реализовали метод getCellContentView?   -  person Kassem    schedule 31.10.2012
comment
@KassemBagher Да - (UITableViewCell *) getCellContentView:(NSString *)cellIdentifier   -  person user1269586    schedule 31.10.2012
comment
вы можете попробовать поместить эту строку NSLog(@в ячейку для строки); внутри метода cellForRowAtIndexPath. и посмотреть, было ли это вызвано   -  person Kassem    schedule 31.10.2012
comment
То, как вы реализовали код, не требует подключения к IBOutlet. Я просто спрашиваю, добавляете ли вы UITableView в представление?   -  person Kassem    schedule 31.10.2012


Ответы (1)


На самом деле мне интересно, откуда вы знаете, что reloadData не вызывается?

Попробуйте поместить какой-нибудь лог в cellForRowAtIndexPath? чтобы увидеть, вызывается или нет, когда вы нажимаете кнопку? а также сделать это:

- (void)reloadTheTB {
   NSLog(@"Test reloadTheTB");
   NSLog(@"%@",dict);
  [[self tableView] reloadData];

}

Соответствует ли содержание вашего словаря тому, что вы ожидаете? или не меняется после loadPlist?

Вероятно, вызов reloadData не выполняется в основном потоке, и вы можете обновить пользовательский интерфейс только в основном потоке. Попробуйте выполнить свой метод в основном потоке, выполнив что-то вроде этого:

-(void)ReloadTheTB{   
  [self.tableView performSelectorOnMainThread@selector(reloadData) withObject:nil waitUntilDone:NO]
}
person oiledCode    schedule 30.10.2012
comment
Содержимое plist, что я ожидаю. Если я сделаю NSLog(@"%@", dict) в cellForRowAtIndexPath, я получу весь свой словарь. Если я сделаю NSLog(@"%@", dict); в - (void)reloadTheTB, в журнале будет только ( )... Я действительно не понимаю, что происходит - person user1269586; 30.10.2012
comment
Цель состоит в том, чтобы понять, видите ли вы сообщение журнала, которое вы помещаете в cellForRowAtIndexPath после вызова reloadData. вы видели сообщение журнала или нет? - person oiledCode; 30.10.2012