【发布时间】:2012-02-19 17:35:00
【问题描述】:
我正在开发一个有购物车的应用。当我在购物车中添加产品时,我的按钮会模态地连接到表格视图控制器。然后当我选择一行时,模式视图控制器应该被关闭。我尝试使用我的委托来实现这一点。这是我的代码:
(无关代码省略)
ItemsTableViewController(可供选择的产品列表)
//the header file
@class ItemsTableViewController;
@protocol ItemsTableViewControllerDelegate <NSObject>
- (void) itemsTableViewController: (ItemsTableViewController *)sender
didSelectProduct: (Product *) aProduct;
@end
@interface ItemsTableViewController : CoreDataTableViewController
@property (nonatomic, strong) UIManagedDocument *itemDatabase;
@property (nonatomic, weak) id <ItemsTableViewControllerDelegate> delegate;
@end
//来自实现的sn-ps
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
Product *item = [self.fetchedResultsController objectAtIndexPath:indexPath];
[self.delegate itemsTableViewController:self didSelectProduct:item];
NSLog(@"DID SELECT ROW AT index %d with name %@", indexPath.row, item.name);
}
//这是我的购物车,ItemsTableViewController 委托
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:@"Show Products List"]){
ItemsTableViewController *itemsTVC = (ItemsTableViewController *)segue.destinationViewController;
itemsTVC.delegate = self;
}
}
- (void) itemsTableViewController:(ItemsTableViewController *)sender didSelectProduct:(Product *)aProduct{
//adds the product in the shopping cart
[self.shoppingCart addObject:aProduct];
[self.products reloadData];
[self dismissModalViewControllerAnimated:YES];
NSLog(@"from the delegate got product %@", aProduct.name);
}
【问题讨论】:
-
运行它时实际发生了什么?你还在哪里调用
NSLog(或断点)来确保你的变量被正确分配并且你的方法被调用(或不被调用)?您的日志记录的输出是什么? -
它记录了一行被选中并且项目被识别但是从代理的部分它没有记录 NSLog(@"from the delegate got product %@", aProduct.name);跨度>
-
你的代表软弱有什么原因吗?
-
所有代表都应该是弱@rokjarc
-
不应该是 __unsafe_unretained 与 ARC 一起使用吗?即:stackoverflow.com/questions/7753841/…
标签: iphone objective-c delegates