【问题标题】:How do I access a Model Object from different viewControllers如何从不同的视图控制器访问模型对象
【发布时间】:2013-04-07 01:14:46
【问题描述】:

我不确定我是否采取了正确的方法,但我想从不同的视图控制器访问我的购物车类模型。我的第一种方法是在每个 viewController 中初始化一个 Cart * 对象,但我想我最终得到了多个购物车对象,而我想要的只是一个可以全局访问的对象。搜索后,我想出了一个看起来更好的不同方法,但还没有运气。

我有一个按钮,可以将交易添加到购物车。但是当我尝试添加它时,该方法没有被调用。这是我的设置方式。

在我的 Cart 类中,我有一个 NSMutableArray 来保存我的交易。

在我的 viewController 中,我设置了 Cart *cart 类型的属性并像这样初始化

@property (strong, nonatomic) Cart *cart;

...

-(id)initWithModel:(Cart *)cart {
    self = [super init];

    if(self){
        self.cart = cart;

    }

    return self;
}

那我的按钮方法是这样的

-(IBAction)addDealToCart {

    NSLog(@"The Cart has %i items", [self.cart qtyOfItemsInCart]);

    NSLog(@"Added the Deal to the Cart");

    [self.cart addDealsToCart:self.deal];

    NSLog(@"The Cart now has %i items", [self.cart qtyOfItemsInCart]);

    self.deal.qtyInCart = self.deal.qtyInCart + 1;
    NSLog(@"the deal has %i items in the Cart", self.deal.qtyInCart);

}

在这一行 addDealsToCart:deal 永远不会被调用。

这是我的购物车类中的 addDealsToCart:deal 方法

-(void)addDealsToCart:(Deals *)deal {
    [self.cartContents addObject:deal];
    NSLog(@"the deal was added to the cart %@",deal);
}

任何帮助都会很棒。谢谢

【问题讨论】:

  • 当你运行你的代码时,NSLog(@"the deal was added to the cart %@",deal); 会被打印出来吗? NSLog(@"Added the Deal to the Cart"); 也有同样的问题?
  • @Barjavel 不,NSLog(@"the deal was added to the cart %@",deal); 不会被调用。这个是NSLog(@"Added the Deal to the Cart");
  • 看来self.cart 可能是nil

标签: ios objective-c


【解决方案1】:

如果不进行整个重新架构,为什么不将购物车对象传递给每个视图控制器?我个人不会走您的描述暗示的单身路线。

更新(示例):

UIViewController *yourNextVC = [[YourNextVC alloc] init];
yourNextVC.cart = self.cart //The current cart in your current vc, passing it along.
[self presentViewController:yourNextVC animated:YES completion:nil];

【讨论】:

  • 看起来不错,我今晚稍后再试试。那你会在根视图控制器中初始化吗?
  • 不确定您的购物车与您的应用程序在哪里发挥作用,但可能在早期(在您早期的 vc 之一中),甚至是您的 UIApplicationDelegate 中的 applicationDidFinishLaunching: 方法。
  • 不过,不确定这是否有助于您的 addDealsToCart 不被调用。我怀疑你有多个购物车实例化(或 nil)。
  • 感谢您的帮助。我真的很喜欢你的方法,但由于某种原因无法让它工作:(但是,我发现了这个并设法让它工作,所以看起来我现在要走单例路线(直到出现更多问题)。 . 无论如何谢谢stackoverflow.com/questions/12168037/…
【解决方案2】:

我只需要一个 Cart 变量贯穿整个应用程序,如果需要,可以在 appDelegate 中使用它

@property (strong, nonatomic) Cart *cart;

取出来很简单

AppDelegate *appDelegateObject=(AppDelegate*)[[UIApplication shareApplication] delegate];
appDelegateObject.cart.qtyOfItemsInCart= 1; //initialize where you want.

像这样在另一个视图控制器中取出:

  AppDelegate *appDelegateObject=(AppDelegate*)[[UIApplication shareApplication] delegate];
  NSLog(@"cart value: %d,appDelegateObject.cart.qtyOfItemsInCart);

【讨论】:

    猜你喜欢
    • 2012-08-23
    • 2016-07-22
    • 2018-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多