Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create View Controller with Parameters

Tags:

objective-c

I would like to create a new viewController and pass data along when I instantiate.

I have a dictionary with some data and would like to access that data as soon as the viewController is created.

I've tried this:

//create the recipe
    myRecipe = [[RecipeCard alloc] init];
        //create a dictionary here...

//call the setRecipeItems method of the recipe I have created
        [myRecipe setRecipeItems: dictionary]

;

The problem is that the setRecipeItems fires before the view did load.

Ideally, I would like to do something like:

myRecipe = [[RecipeCard alloc] initWithData:dictionary];

But that hasn't worked for me

Thanks

like image 552
Buyin Brian Avatar asked Jan 14 '11 20:01

Buyin Brian


People also ask

How do I instantiate a view controller?

In the Storyboard, select the view controller that you want to instantiate in code. Make sure the yellow circle is highlighted, and click on the Identity Inspector. Set the custom class as well as the field called "Storyboard ID". You can use the class name as the Storyboard ID.


1 Answers

You can do exactly what you are asking by doing this: (place this in your .h file)

@interface RecipeCard : UIViewController {
  NSDictionary *recipes;
}

- (id)initWithRecipes:(NSDictionary *)Recipes;

@end

(Then in your .m file)

@implementation RecipeCard

- (id)initWithRecipes:(NSDictionary *)Recipes
{
  if(self = [super init]) {
    recipes = [NSDictionary dictionaryWithDictionary:Recipes];
    [recipes retain];
  }
  return self;
}

@end

Now you can create your RecipeCard like this:

myRecipe = [[RecipeCard alloc] initWithRecipes:someDictionaryObject];
like image 165
theChrisKent Avatar answered Oct 15 '22 01:10

theChrisKent