使用参数创建视图控制器

时间:2011-01-14 20:08:31

标签: objective-c

我想在实例化时创建一个新的viewController并传递数据。

我有一个包含一些数据的字典,并希望在创建viewController后立即访问该数据。

我试过这个:

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

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

;

问题是setRecipeItems在视图加载之前触发。

理想情况下,我想做类似的事情:

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

但这对我没有用

由于

1 个答案:

答案 0 :(得分:4)

通过这样做,您可以完全按照要求执行操作: (将其放在.h文件中)

@interface RecipeCard : UIViewController {
  NSDictionary *recipes;
}

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

@end

(然后在您的.m文件中)

@implementation RecipeCard

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

@end

现在您可以像这样创建RecipeCard:

myRecipe = [[RecipeCard alloc] initWithRecipes:someDictionaryObject];