将数组传递给另一个视图

时间:2013-01-27 15:12:29

标签: iphone objective-c arrays nsmutablearray

我是xcode的新手。我试图将数组从一个视图传递到另一个视图。我想将ProfileViewController中的整数profileid传递给FavouritesViewController中的数组。 加载FavouritesViewController后,日志将显示数组。

这是我的代码:

ProfileViewController.h

- (IBAction)AddFavouritesClicked:(id)sender;

ProfileViewController.m

@synthesize profileid;


int profileid = 0;

- (IBAction)AddFavouritesClicked:(id)sender {

    FavouritesViewController *favController = [[FavouritesViewController alloc]init];
    [favController.favouritesArray initWithObjects:[NSNumber numberWithInt:profileid], nil];
    NSLog(@"%@", favController.favouritesArray);


}

FavouritesViewController.h

@interface FavouritesViewController : UITableViewController
{
    NSMutableArray *favouritesArray;
}

@property(nonatomic, retain)NSArray *favouritesArray;
@end

FavouritesViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"%@", favouritesArray);
}

到目前为止,favouritesArray值始终为null

非常感谢任何帮助。提前谢谢!

每次点击Addtofavoutites按钮

时,这是我的日志
2013-01-27 22:54:52.865 Ad&Promo[8058:c07] (
2
)
2013-01-27 22:56:10.958 Ad&Promo[8058:c07] (
2
)
2013-01-27 22:56:11.705 Ad&Promo[8058:c07] (
2
)
2013-01-27 22:56:12.191 Ad&Promo[8058:c07] (
2
)

但我希望它看起来像这样......

2013-01-27 22:54:52.865 Ad&Promo[8058:c07] (
2,2,2,2
)

2 个答案:

答案 0 :(得分:2)

你没有指定指针而你错过了alloc方法,这样做:

favController.favouritesArray=[[NSArray alloc]initWithObjects:[NSNumber numberWithInt:profileid], nil];

答案 1 :(得分:2)

首先,您应该查看阵列创建的语法。它应该是:

favController.favouritesArray = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:profileid], nil];

但是,这一点不会解决你的问题,我猜是

这是S.O.上出现的一个典型错误。在以下2个陈述中:

FavouritesViewController *favController = [[FavouritesViewController alloc]init];
favController.favouritesArray = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:profileid], nil];

您正在分配新的FavouritesViewController。这与您已在应用中初始化的任何其他FavouritesViewController无关。这解释了为什么它的内部数组是空的。

您需要做的是让您的ProfileViewController实例了解您的FavouritesViewController实例(而不是在前者实例化后者的私有实例)。

因此,只需在FavouritesViewController内定义ProfileViewController属性,并正确初始化它。然后你就可以做到:

- (IBAction)AddFavouritesClicked:(id)sender {

    self.favController.favouritesArray = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:profileid], nil];

}

这将设置您需要设置到另一个视图控制器中的值。

编辑:

针对此类要求的更好设计是使用模型(如在模型 - 视图 - 控制器中)。

不是让两个控制器中的一个了解另一个,而是创建一个新类(模型),负责保存应用中的所有共享数据。

此类可以从您应用中的任何其他类访问,以便他们可以设置并获取它存储的数据。

这个班可以是一个单身人士:

[MyModel sharedModel].favArray = ...

或者它可以是仅暴露类方法的类,例如:

[MyModel setFavArray:...];
相关问题