【发布时间】:2013-02-07 00:49:09
【问题描述】:
我目前正在尝试从 NSNotification 更新 TableViewController 上的 NSMutableArray 属性,但遇到问题。
我在 Observer 类 .h 文件中声明了我的属性,如下所示:
@property (nonatomic,strong) NSMutableArray *cart;
在 Observer 类 .m 文件中合成:
@synthesize cart = _cart;
我在 Observer 类的 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 每次都发生,而不是第一次发生。
你能告诉我我在这里缺少什么吗?非常感谢您对此问题的意见。
谢谢, 迈克
【问题讨论】:
-
您需要先设置数组,然后再将其放入文件中。
-
我看不出这段代码有什么问题。尝试在向 self.cart 添加项目后立即记录它,然后查看它显示的内容。
-
另外,您是否看到“self.cart == nil”被多次打印(或“self.cart != nil”,就此而言。awakeFromNib 应该只被调用一次,除非您的类正在被释放)?
-
@rdelmar - 每次向其中添加项目时,我都会看到“self.cart == nil”。
-
这意味着这个类正在被释放。你是如何创建这个类的?你是从另一个类分配初始化它吗?
标签: ios objective-c nsmutablearray uitableview nsnotificationcenter