1

我目前正在尝试从 NSNotification 更新 TableViewController 上的 NSMutableArray 属性,但遇到问题。

我在 Observer 类 .h 文件中声明了我的属性,如下所示:

@property (nonatomic,strong) NSMutableArray *cart;

在 Observer 类 .m 文件中合成:

@synthesize cart = _cart;

我在观察者类的 AwakeFromNib 方法中收到通知:

- (void)awakeFromNib{

if (!self.cart){
    NSLog(@"self.cart == nil");
    self.cart = [[NSMutableArray alloc] init];
}else{
    NSLog(@"self.cart != nil");
}

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addCurrentItemToCartFromNotification:) name:@"ItemAddedToCart" object:nil];
}

请注意,在收到通知之前,我正在上述 AwakeFromNib 方法中执行我的 NSMutableArray 属性的 alloc init。

这是在收到通知时调用的方法:

- (void)addCurrentItemToCartFromNotification:(NSNotification *)notification{

 NSDictionary *currentItem = [notification.userInfo objectForKey:@"CART_ITEM_INFORMATION"];

[self.cart addObject:currentItem];
[self.tableView reloadData];

}

然后,我拥有基于我的 NSMutableArray 属性的 tableview 数据源方法,该属性在通知中的上述方法中更新。

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"itemInCart";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

// Configure the cell...
NSDictionary *cartItem = [self.cart objectAtIndex:indexPath.row];
cell.textLabel.text = [cartItem objectForKey:@"ITEM_NAME"];

return cell;
}

我对程序的预期行为是在收到通知时更新我的​​ NSMutable 数组属性(由于 if (!self.cart) 条件,alloc init 应该只在第一次发生)

但是发生的事情是每次我收到通知时,都会删除 NSMutableArray 中的对象并添加新对象而不是附加对象。因此,在任何时间点,NSMutableArray 只包含最近一次通知接收到的对象。

我认为 alloc init 每次都发生,而不是第一次发生。

你能告诉我我在这里缺少什么吗?我非常感谢您在这个问题上的投入。

谢谢,迈克

4

2 回答 2

0

每次添加条目时都会记录“self.cart == nil”这一事实意味着每次添加条目时都会调用 awakeFromNib,这反过来意味着您正在创建 Observer 类的新实例每一次。所以这就是问题所在,而不是您帖子中的任何代码。为了解决这个问题,我们需要知道你是如何创建这个类的。

于 2013-02-07T05:01:17.147 回答
0

不知道为什么您会看到该数组被重新分配(如果这是发生的事情),但这无论如何都需要一种不同的模式:我会通过替换合成的 setter 来懒惰地初始化您的购物车属性......

- (NSArray *)cart {
    if (!_cart) {
        _cart = [NSMutableArray array];
    }
    return _cart;
}

删除 awakeFromNib 中的购物车内容,并始终引用 self.cart(init 和 dealloc 除外)。

于 2013-02-07T01:10:09.997 回答