将数组的内容从一个类传递到另一个类

时间:2011-04-13 03:11:49

标签: iphone

我在DetailView类中有一个填充小tableView的数组,当用户按下一个按钮时,我需要将数组发送到另一个View Controller,在那里填充tableView,但是我遇到了一些困难让它工作。这就是我到目前为止所做的事情:

*DetailViewController.m*

    #import "DetailViewController.h"
    #import "OtherViewController.h"


-(IBAction) toCart:(id)sender {

    OtherViewController *oVC = [[OtherViewController alloc] init];
    oVC.shoppingList = sList;
    NSLog(@"Ingredients count %d", [sList count]); //This returns a number, so the sList definitely contains values, and the method is definitely being called.
    [oVC release];

}

*OtherViewController.m*

    #import "OtherViewController.h"
    #import "DetailViewController.h"

    @synthesize shoppingList;

-(void) viewWillAppear: (BOOL)animated {
    NSLog(@"list count: %d", [shoppingList count]); // This returns 0

}

sList在类的其他地方填充,sList和shoppingList都在各自的.h文件中声明,使用@property(非原子,保留)......

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

当您拥有taBbarcontroller时,您可以按以下步骤操作:

viewControllers中为您创建tabbar(与topViewController appDelegate相关联)的引用。

otherViewController = [[tabBarController.viewControllers objectAtIndex:<tabIndex>] topViewController];

在appDelegate中将其设为@property,以便您可以在应用中的任意位置访问它。

现在,

-(IBAction) toCart:(id)sender {

    //appDelegate <--- get reference to your application delegate using [[UIApplication sharedApplicaiton]delegate] do not forget to properly type cast it.

    OtherViewController *oVC = [appDelegate otherViewController];
    oVC.shoppingList = sList;
    NSLog(@"Ingredients count %d", [sList count]); 
//This returns a number, so the sList definitely contains values, and the method is definitely being called.
   // [oVC release]; no need to release it...

}


//also make sure you do not initialize shoppingList of otherViewController in viewDidLoad(or any other method) of otherViewController, else it will be overwritten(lost its previous reference).
appDelegate's .h

@property OtherViewController *otherViewController;
appDelegate's.m

中的

@synthesize otherViewController;
appDelegates中的

m(方法didFinishLaunchingWithOptions:)写

otherViewController = [[tabBarController.viewControllers objectAtIndex:<tabIndex>] topViewController];

由于

答案 1 :(得分:0)

toCart:中,您正在创建OtherViewController,然后立即将其丢弃。无论OtherViewController正在调用-viewWillAppear,它都不是您在toCart:中创建的那个。该对象是如何创建并放在屏幕上的?你需要一个指向它的指针来修改它。

但更好的方法是将模型数据移出视图控制器并将其放在单个ShoppingCart对象中。然后所有的视图控制器都会引用它(或者如果在你的程序中有意义,你可以使ShoppingCart成为单例)。这样,只要您从任何地方更改购物车,所有视图都将正确更新,而无需告知每个视图控制器所有其他视图控制器。