2013-03-28 2 views
0

Я создаю UITableView в контроллере UIViewНевозможно reloaddata (UITableView)

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 470, self.view.frame.size.height) style:UITableViewStylePlain]; 
    self.tableView.dataSource = self; 
    self.tableView.delegate = self; 
    [self.view addSubview:self.tableView]; 
    NSLog(@"tableView is '%@'",self.tableView); 
} 

результат NSLog: "Tableview является" < UITableView: 0x7c60c00; каркасные = (0 0; 470; 1004) clipsToBounds = ДА; gestureRecognizers =; = слой; contentOffset: {0, 0}> '»

метод refreshTableView будет называться, когда itemArray модифицирована другим контроллером

**SideBarViewController *sideBarViewController = [[SideBarViewController alloc]init]; 
[sideBarViewController refreshTableView];** 

-(void)refreshTableView { 
    [self createItemArray]; 
    NSLog(@"reload itemArray->%@",self.itemArray); 
    NSLog(@"tableView is '%@'",self.tableView); 
    [self.tableView reloadData]; 
} 

как-то, результат NSLog станет: «tableView is '(null)'". и tableView не будет перезагружен.

Почему? пожалуйста помоги. Благодарю.

Update:

NSLog из itemArray было прекрасно:

до изменения перезарядка itemArray -> ( "test.md" )

после изменения перезарядка itemArray-> ( "test.md", "test2.md" )

Update2:

#pragma mark - Table view data source 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    cell.textLabel.text = [self.itemArray objectAtIndex:indexPath.row]; 
    return cell; 
} 

обновление 3:

.h 
@interface SideBarViewController : UIViewController<IIViewDeckControllerDelegate,UITableViewDataSource,UITableViewDelegate> 

.m 
@interface SideBarViewController() 
@property (nonatomic,strong) UITableView *tableView; 
@end 

@implementation SideBarViewController 
@synthesize tableView = _tableView; 

изменение 4:

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath 

метод работает нормально, после того, как удалена строк, TableView было перезагружается.

+0

перед перезагрузкой стола, его работа прекрасна ?? – iPatel

+0

Да, отлично работает, табличное представление нельзя перезагрузить –

+1

Код, который вы предоставили, выглядит просто замечательно - ошибка должна быть в другом месте вашего кода. – ColinE

ответ

0

Вы можете попробовать использовать Notification

  1. добавить наблюдателя в вас viewDidLoad в Sidebarvc

    [[NSNotificationCenter defaultCenter] addObserver: автономный селектор: @selector (refreshTableView :) имя : @ "dataChanged" объект: ноль];

  2. создать метод для обновления

    - (Недействительными) refreshTableView: (NSNotification *) Notif { }

  3. на другой ВК, просто ждать уведомления

    [[NSNotificationCenter defaultCenter] postNotificationName: @ "dataChanged" объект: nil];

забудьте не содержание 4.do очистить его

add [[NSNotificationCenter defaultCenter] removeObserver:self]; to ViewDidUnload 

Должно работать.

1

Поделитесь еще несколькими кодами, чтобы мы могли найти точный номер.

Вы можете проверить фактическое имя вашего TableView? поделитесь некоторым кодом таблицы, которую вы объявили в файле .h.

Проверить массив, данные доступны до перезагрузки или обновления, а методы представления таблиц работают нормально.

Проверьте, назначены ли делегаты tableView в файле .h или нет? И реализовать методы делегата от Tableview в своем классе должным образом ..

@interface MyViewController: UIViewController

И еще одну вещь проверить, что вы правильно реализовать ваши методы источника данных и delagate.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath. 

Если вы сделали это правильно, проверьте свой массив перед загрузкой данных. Может быть, это поможет вам.

+0

Спасибо, обновил мой пост. –

+0

Обновлено, пожалуйста, проверьте обновление 3, спасибо –

+0

Проверьте, получаете ли вы предупреждение в xcode? – Nirav

0
// 
    // ViewController.h 
    // tableData 
    // 
    // Created by Nirav Jain on 3/28/13. 
    // Copyright (c) 2013 SI. All rights reserved. 
    // 

    #import <UIKit/UIKit.h> 

    @interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate> 
    { 
     int rows; 
    } 
    @end 


// tableData 
// 
// Created by Nirav Jain on 3/28/13. 
// Copyright (c) 2013 SI. All rights reserved. 
// 

#import "ViewController.h" 

//@implementation SideBarViewController 


@interface ViewController() 
@property (nonatomic,strong) UITableView *tableView; 
@end 

@implementation ViewController 

@synthesize tableView = _tableView; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 470, self.view.frame.size.height) style:UITableViewStylePlain]; 
    self.tableView.dataSource = self; 
    self.tableView.delegate = self; 
    [self.view addSubview:self.tableView]; 
    NSLog(@"tableView is '%@'",self.tableView); 
    rows = 5; 


    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonItemStyleDone target:self action:@selector(refreshTableView)]; 
} 


-(void)refreshTableView { 

    rows = 12; 
    NSLog(@"tableView is '%@'",self.tableView); 
    [self.tableView reloadData]; 
} 
#pragma mark - Table view data source 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return rows; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    cell.textLabel.text = [ NSString stringWithFormat: @"%d", indexPath.row]; 
    return cell; 
} 

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

@end 
+0

Том проверить этот код. код работает отлично для меня. – Nirav

+0

Я закончил с моими любимицами ... :) – Nirav

+0

Большое спасибо, я пытаюсь –

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