错误的对象添加到UITableView

时间:2016-06-01 13:07:12

标签: ios objective-c uitableview

在我的应用中,我通过NSNotificationCenter(另一个控制器)获取一个对象并将对象添加到UITableView

-(void)viewWillAppear:(BOOL)animated 
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RosterSave:) name:@"RosterSave" object:nil];
}

-(void)RosterSave:(NSNotification *)notification
{
    NewRoster* newRoster = [[NewRoster alloc]init];
    newRoster = notification.object;
    [myUser.rosterArray addObject:newRoster];
    [self.myRoster reloadData];
}

这是tableView方法:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return myUser.rosterArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    NSString *iden = @"MyTable";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:iden];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iden];
    }
    NewRoster* myNewRoster = [myUser.rosterArray objectAtIndex:indexPath.row];
    cell.textLabel.text = myNewRoster.nameRoster;
    return cell;
}

当用户添加第一个对象时,tableView获取自己的行。当用户添加第二个对象时,它会以这种方式添加第二个对象的两行。

如何解决此问题?

3 个答案:

答案 0 :(得分:1)

您已在observer(notification)中添加viewWillAppear,每次出现视图时都会被调用。

viewDidLoad而不是viewwillAppear中添加通知。

答案 1 :(得分:1)

我总是喜欢在dealloc中的init /和unsubscriptions中放置NSNotification订阅。此模式易于阅读和调试。此外,它保证您永远不会双重订阅或双重取消订阅。

在您的情况下,您很容易在viewWillAppear

中创建多个订阅
- (instancetype)init
{
    ...
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RosterSave:) name:@"RosterSave" object:nil];
    ...
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

答案 2 :(得分:0)

@Feroz是关于您分配新对象并将其替换为notification.object的。 @Lion是关于viewDidLoad与viewDidAppear的关系您正在生成多个通知。您只需要为每个对象生成一个。在RosterSave代码中放置一个断点,并计算每个新对象调用的次数。还要查看堆栈跟踪以查看谁正在生成这些调用。这可以归结为一个简单的问题,即逐步理解代码,了解正在发生的事情。