AとBの2つのタブを持つタブバーコントローラーがあります。タブAは通常のUIViewControllerで、タブBはTableViewControllerです。タブAからNSNotificationを投稿して同じものを受け取り、タブBのテーブルにデータを表示しようとしています.
以下のように、タブ A からの通知を投稿します。
//"itemAddedToCartDictionary" is the object that I am sending with notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"ItemAddedToCart" object:nil userInfo:itemAddedToCartDictionary];
私のタブ B (TableViewController) で、上記の通知を NSMutableArray プロパティの更新として受信しようとしています。プロパティは次のように宣言されます。
タブ B - .h ファイル:
@property (nonatomic,strong) NSMutableArray *cart;
タブ B - .m ファイル:
//providing manual setter method for 'items' hence not using @synthesize
- (void)setCart:(NSMutableArray *)cart{
_cart = cart;
[self.tableView reloadData];
}
ここで、以下のように、(タブ B で) 通知を受け取るためのコードを AwakeFromNib に配置しました。
- (void)awakeFromNib{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addCurrentItemToCartFromNotification:) name:@"ItemAddedToCart" object:nil];
}
このコードは、プロパティを更新する通知を受け取ると、メソッド「addCurrentItemToCartFromNotification」を呼び出します。
- (void)addCurrentItemToCartFromNotification:(NSNotification *)notification{
NSDictionary *currentItem = [notification.userInfo objectForKey:@"CART_ITEM_INFORMATION"];
if (!self.cart){
NSLog(@"self.cart == nil");
self.cart = [[NSMutableArray alloc] init];
}else{
NSLog(@"self.cart != nil");
}
[self.cart addObject:currentItem];
}
今、これは私が直面している問題です:
タブ A に通知を投稿した後、受信した通知から上記のメソッドでプロパティを更新しても、タブ B (TableViewController) にデータが表示されません。私の 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];
NSDictionary *cartItem = [self.cart objectAtIndex:indexPath.row];
cell.textLabel.text = [cartItem objectForKey:@"ITEM_NAME"];
return cell;
}
したがって、基本的に、データソースメソッドから TableViewController (通知から受信および更新している) のプロパティにアクセスしていますが、データは返されません。
ここでどこが欠けているのか教えてください。
ありがとう、マイク
編集: @Joel、@martin、@mkirci からの応答に続いて
私の「addCurrentItemToCartFromNotification」(通知の受信時に呼び出されるメソッド)にリロードデータを追加すると役立ちました。タブ B (TableViewController) で通知から受け取ったアイテムを確認できるようになりました。
ここで何が起こっているかです:
通知が受信されるたびに、NSMutableArray プロパティは nil として返されます。したがって、通知を受信するたびに、(初回だけではなく) NSMutableArray プロパティに対して (addCurrentItemToCartFromNotification で) alloc init が発生します。したがって、通知から受け取ったオブジェクトで配列をインクリメントする代わりに、配列は毎回再作成され、現在の通知からのオブジェクトのみが追加されます。
この状況に光を当ててください。すべての回答に感謝します。
ありがとう、マイク
EDIT2
@Joel からの提案のために initwithnibname 用に切り取られた更新されたコード
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
if (!self.cart){
NSLog(@"self.cart == nil");
self.cart = [[NSMutableArray alloc] init];
}else{
NSLog(@"self.cart != nil");
}
return self;
}