我目前正在尝试从 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 每次都发生,而不是第一次发生。
你能告诉我我在这里缺少什么吗?我非常感谢您在这个问题上的投入。
谢谢,迈克