I am a newbie in xcode. I am trying to pass an array from one view to another. I want to pass an integer profileid in the ProfileViewController to an array in the FavouritesViewController.
Once the FavouritesViewController is loaded the log will display the array.
Here’s my code:
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);
}
So far the favouritesArray value is always null
Any help would be very much appreciated. Thanks in advance!
Here is my Log every time I clicked the Addtofavoutites button
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
)
But instead I want it to look like this..
2013-01-27 22:54:52.865 Ad&Promo[8058:c07] (
2,2,2,2
)
First of all, you should review the syntax for your array creation. It should be:
This alone will not fix your issues, though, I gues
This is quite a typical error that shows up here on S.O. In the following 2 statements:
you are allocating a new
FavouritesViewController. That has nothing to do with any otherFavouritesViewControllerthat you have already initialized in your app. That explain why its internal array is empty.What you need to do is make your
ProfileViewControllerinstance aware of your FavouritesViewController instance (as opposed to instantiating a private instance of the latter inside the former).So, simply define a
FavouritesViewControllerproperty inside ofProfileViewController, and initialize it properly. Then you will be able to do:}
and this will set the value you need to set into the other view controller you have.
EDIT:
a better design for this kind of requirement is using a model (as in model-view-controller).
Instead of letting one of the two controllers know about the other, you create a new class (the model) responsible for holding all the shared data in your app.
This class would be accessible from any other class in your app, so that they could set and get the data it stores.
This class could be a singleton:
or it could be a class exposing only class methods, e.g.: