現在、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 プロパティに基づいて、テーブルビュー データソース メソッドを作成します。
- (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 は、初めてではなく、毎回発生していると考えています。
ここで何が欠けているのか教えてください。この問題に関するご意見をお待ちしております。
ありがとう、マイク