1

我是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);


}

收藏夹ViewController.h

@interface FavouritesViewController : UITableViewController
{
    NSMutableArray *favouritesArray;
}

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

收藏夹ViewController.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
)
4

2 回答 2

1

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

favController.favouritesArray=[[NSArray alloc]initWithObjects:[NSNumber numberWithInt:profileid], nil];
于 2013-01-27T15:19:03.160 回答
1

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

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

不过,我认为仅此一项并不能解决您的问题

这是一个非常典型的错误,出现在 SO 在以下 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:...];
于 2013-01-27T15:21:19.987 回答