【问题标题】:Multiple segues not passing Object data between themselves多个 segues 在它们之间不传递对象数据
【发布时间】:2012-08-21 10:27:19
【问题描述】:

我已经开始了一个项目,该项目最初是按照 Appcoda 关于使用视图控制器在场景之间传递数据的教程完成的(在此处查找:http://www.appcoda.com/storyboards-ios-tutorial-pass-data-between-view-controller-with-segue/

基本上,它从第一个场景中获取表格数据,然后 segue 连接到另一个控制器,该控制器显示配方图像、准备时间和成分。然而,我想更进一步,添加另一个视图控制器,显示如何准备配方的说明。所以到目前为止的失败是:

初始视图控制器(表格数据) -> recipeDetailViewController -> instructionsViewContoller

所以实际上只有三个视图控制器,但它们都共享相同的数据。我想在视图控制器之间共享的数据是配方数据,格式如下:

Recipe *recipe1 = [Recipe new];
recipe1.name = @"Egg Benedict";
recipe1.prepTime = @"30 min";
recipe1.imageFile = @"egg_benedictl.jpg";
recipe1.ingredients = [NSArray arrayWithObjects:@"2 fresh English muffins", @"4 eggs",    @"4 rashers of back bacon", @"2 egg yolks", @"1 tbsp of lemon juice", @"125 g of butter", @"salt and pepper", nil];
recipe1.instructions = @"This is recipe one's instruction set";

当然还有这个相关的代码:

self.title = recipe.name;
self.prepTimeLabel.text = recipe.prepTime;
self.recipePhoto.image = [UIImage imageNamed:recipe.imageFile];

NSMutableString *ingredientText = [NSMutableString string];
for (NSString* ingredient in recipe.ingredients) {
    [ingredientText appendFormat:@"%@\n", ingredient];
}
self.ingredientTextView.text = ingredientText;

self.instructionTextView.text = recipe.instructions;

recipeLabel.text = recipeName;

但是,当我尝试将配方的说明传递给我的第三个视图控制器时,得到的结果好坏参半。要么什么都没有传递,要么传递拉丁文本字段占位符,要么只传递第一个食谱的 recipe.instruction 用于所有食谱,无论选择了什么。我已经在这里待了一个星期,我认为是时候寻求希望了。

如果有人对如何在多个 segue 之间传递我的食谱数据有任何建议,我将不胜感激。我已将所有代码粘贴在下面,从顶部文件开始:

//
//  minuteMealsViewController.h
//  minuteMeals
//
//  Created by KMO on 8/18/12.
//  Copyright (c) 2012 KAM Digital. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "Recipe.h"

@interface minuteMealsViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) IBOutlet UITableView *tableView;
//@property (nonatomic, weak) IBOutlet UIImageView *thumbnailImageView;



@end

//
//  minuteMealsViewController.m
//  minuteMeals
//
//  Created by KMO on 8/18/12.
//  Copyright (c) 2012 KAM Digital. All rights reserved.
//

#import "minuteMealsViewController.h"
#import "minuteMealsDetailViewController.h"
#import "Recipe.h"

@interface minuteMealsViewController ()

@end

@implementation minuteMealsViewController {
    NSArray *recipes;
    NSArray *thumbnails;
    NSArray *recipeTitle;
}
@synthesize tableView;


//@synthesize thumbnailImageView;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Initialize table data

    Recipe *recipe1 = [Recipe new];
    recipe1.name = @"Egg Benedict";
    recipe1.prepTime = @"30 min";
    recipe1.imageFile = @"egg_benedictl.jpg";
    recipe1.ingredients = [NSArray arrayWithObjects:@"2 fresh English muffins", @"4 eggs", @"4 rashers of back bacon", @"2 egg yolks", @"1 tbsp of lemon juice", @"125 g of butter", @"salt and pepper", nil];
    recipe1.instructions = @"This is recipe one's instruction set";

    Recipe *recipe2 = [Recipe new];
    recipe2.name = @"Mushroom Risotto";
    recipe2.prepTime = @"30 min";
    recipe2.imageFile = @"mushroom_risottol.jpg";
    recipe2.ingredients = [NSArray arrayWithObjects:@"1 tbsp dried porcini mushrooms", @"2 tbsp olive oil", @"1 onion, chopped", @"2 garlic cloves", @"350g/12oz arborio rice", @"1.2 litres/2 pints hot vegetable stock", @"salt and pepper", @"25g/1oz butter", nil];
    recipe2.instructions = @"This is recipe two's instruction set";

    Recipe *recipe3 = [Recipe new];
    recipe3.name = @"Full Breakfast";
    recipe3.prepTime = @"20 min";
    recipe3.imageFile = @"full_breakfastl.jpg";
    recipe3.ingredients = [NSArray arrayWithObjects:@"2 sausages", @"100 grams of mushrooms", @"2 rashers of bacon", @"2 eggs", @"150 grams of baked beans", @"Vegetable oil", nil];

    Recipe *recipe4 = [Recipe new];
    recipe4.name = @"Hamburger";
    recipe4.prepTime = @"30 min";
    recipe4.imageFile = @"hamburgerl.jpg";
    recipe4.ingredients = [NSArray arrayWithObjects:@"400g of ground beef", @"1/4 onion (minced)", @"1 tbsp butter", @"hamburger bun", @"1 teaspoon dry mustard", @"Salt and pepper", nil];

    Recipe *recipe5 = [Recipe new];
    recipe5.name = @"Ham and Egg Sandwich";
    recipe5.prepTime = @"10 min";
    recipe5.imageFile = @"ham_and_egg_sandwichl.jpg";
    recipe5.ingredients = [NSArray arrayWithObjects:@"1 unsliced loaf (1 pound) French bread", @"4 tablespoons butter", @"2 tablespoons mayonnaise", @"8 thin slices deli ham", @"1 large tomato, sliced", @"1 small onion", @"8 eggs", @"8 slices cheddar cheese", nil];

    Recipe *recipe6 = [Recipe new];
    recipe6.name = @"Creme Brelee";
    recipe6.prepTime = @"1 hour";
    recipe6.imageFile = @"creme_breleel.jpg";
    recipe6.ingredients = [NSArray arrayWithObjects:@"1 quart heavy cream", @"1 vanilla bean, split and scraped", @"1 cup vanilla sugar", @"6 large egg yolks", @"2 quarts hot water", nil];

    Recipe *recipe7 = [Recipe new];
    recipe7.name = @"White Chocolate Donut";
    recipe7.prepTime = @"45 min";
    recipe7.imageFile = @"white_chocolate_donutl.jpg";
    recipe7.ingredients = [NSArray arrayWithObjects:@"3 1/4 cups flour", @"2 teaspoons baking powder", @"1/4 teaspoon salt", @"2 beaten eggs", @"2/3 cup sugar", @"2 ounces melted white chocolate", @"1/2 cup milk", nil];

    Recipe *recipe8 = [Recipe new];
    recipe8.name = @"White Chocolate Mocha";
    recipe8.prepTime = @"5 min";
    recipe8.imageFile = @"starbucks_coffeel.jpg";
    recipe8.ingredients = [NSArray arrayWithObjects:@"2/3 cup whole milk", @"6 tablespoons white chocolate chips", @"coffee", @"whipped cream", nil];

    Recipe *recipe9 = [Recipe new];
    recipe9.name = @"Vegetable Curry";
    recipe9.prepTime = @"30 min";
    recipe9.imageFile = @"vegetable_curryl.jpg";
    recipe9.ingredients = [NSArray arrayWithObjects:@"1 tablespoon olive oil", @"1 onion, chopped", @"2 cloves garlic", @"2 1/2 tablespoons curry powder", @"2 quarts hot water", nil];

    Recipe *recipe10 = [Recipe new];
    recipe10.name = @"Instant Noodle with Egg";
    recipe10.prepTime = @"8 min";
    recipe10.imageFile = @"instant_noodle_with_eggl.jpg";
    recipe10.ingredients = [NSArray arrayWithObjects:@"1 pack of Instant Noodle", @"2 eggs", nil];

    Recipe *recipe11 = [Recipe new];
    recipe11.name = @"Noodle with BBQ Pork";
    recipe11.prepTime = @"20 min";
    recipe11.imageFile = @"noodle_with_bbq_porkl.jpg";
    recipe11.ingredients = [NSArray arrayWithObjects:@"1 pack of Instant Noodle", @"BBQ pork", @"Salt and Pepper", nil];

    Recipe *recipe12 = [Recipe new];
    recipe12.name = @"Japanese Noodle with Pork";
    recipe12.prepTime = @"20 min";
    recipe12.imageFile = @"japanese_noodle_with_porkl.jpg";
    recipe12.ingredients = [NSArray arrayWithObjects:@"1 pack of Japanese Noodle", @"2 green onions", @"2 garlic cloves, minced", @"4 boneless pork loin chops", nil];

    Recipe *recipe13 = [Recipe new];
    recipe13.name = @"Green Tea";
    recipe13.prepTime = @"5 min";
    recipe13.imageFile = @"green_teal.jpg";
    recipe13.ingredients = [NSArray arrayWithObjects:@"Green tea", nil];

    Recipe *recipe14 = [Recipe new];
    recipe14.name = @"Thai Shrimp Cake";
    recipe14.prepTime = @"1.5 hours";
    recipe14.imageFile = @"thai_shrimp_cakel.jpg";
    recipe14.ingredients = [NSArray arrayWithObjects:@"8 oz (250g) peeled and deveined raw shrimp", @"2 tablespoons red curry paste", @"1 large egg", @"2 teaspoon fish sauce", @"1 tablespoon sugar", @"2 tablespoons coconut milk", @"2 tablespoons roughly chopped Thai basil leaves", nil];

    Recipe *recipe15 = [Recipe new];
    recipe15.name = @"Angry Birds Cake";
    recipe15.prepTime = @"4 hours";
    recipe15.imageFile = @"angry_birds_cakel.jpg";
    recipe15.ingredients = [NSArray arrayWithObjects:@"12 tablespoons (1 1/2 sticks) unsalted butter", @"2 1/2 cups all-purpose flour", @"1 tablespoon baking powder", @"1 teaspoon salt", @"1 3/4 cups sugar", @"2 large eggs, plus 3 large egg yolks", @"1 cup of milk", nil];

    Recipe *recipe16 = [Recipe new];
    recipe16.name = @"Ham and Cheese Panini";
    recipe16.prepTime = @"10 min";
    recipe16.imageFile = @"ham_and_cheese_paninil.jpg";
    recipe16.ingredients = [NSArray arrayWithObjects:@"2 tablespoons unsalted butter", @"4 cups thinly sliced shallots", @"2 teaspoons fresh thyme", @"1/4 cup grainy Dijon mustard", @"8 slices rustic white bread", @"8 slices Gruyere cheese", @"8 ounces sliced cooked ham", nil];

    recipeTitle = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil];


    recipes = [NSArray arrayWithObjects:recipe1, recipe2, recipe3, recipe4, recipe5, recipe6, recipe7, recipe8, recipe9, recipe10, recipe11, recipe12, recipe13, recipe14, recipe15, recipe16, nil];



    thumbnails = [NSArray arrayWithObjects:@"egg_benedict.jpg", @"mushroom_risotto.jpg", @"full_breakfast.jpg", @"hamburger.jpg", @"ham_and_egg_sandwich.jpg", @"creme_brelee.jpg", @"white_chocolate_donut.jpg", @"starbucks_coffee.jpg", @"vegetable_curry.jpg", @"instant_noodle_with_egg.jpg", @"noodle_with_bbq_pork.jpg", @"japanese_noodle_with_pork.jpg", @"green_tea.jpg", @"thai_shrimp_cake.jpg", @"angry_birds_cake.jpg", @"ham_and_cheese_panini.jpg", nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [recipeTitle count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"RecipeCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
    cell.textLabel.text = [recipeTitle objectAtIndex:indexPath.row];
    cell.imageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];

    return cell;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showRecipeDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];

        minuteMealsDetailViewController *destViewController = segue.destinationViewController;

        destViewController.recipe = [recipes objectAtIndex:indexPath.row];
    }
    NSLog(@"showRecipeDetial Segue is being passed");
}

- (void)viewDidUnload
{
    [self setTableView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

@end

//
//  minuteMealsDetailViewController.h
//  minuteMeals
//
//  Created by KMO on 8/18/12.
//  Copyright (c) 2012 KAM Digital. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "Recipe.h"

@interface minuteMealsDetailViewController : UIViewController

@property (strong, nonatomic) IBOutlet UIImageView *recipePhoto;

@property (strong, nonatomic) IBOutlet UILabel *prepTimeLabel;

@property (strong, nonatomic) IBOutlet UITextView *ingredientTextView;

@property (nonatomic, strong) IBOutlet UILabel *recipeLabel;

@property (nonatomic, strong) NSString *recipeName;

@property (nonatomic, strong) Recipe *recipe;

@property (strong, nonatomic) IBOutlet UITextView *instructionTextView;



@end

//
//  minuteMealsDetailViewController.m
//  minuteMeals
//
//  Created by KMO on 8/18/12.
//  Copyright (c) 2012 KAM Digital. All rights reserved.
//

#import "minuteMealsViewController.h"
#import "minuteMealsDetailViewController.h"
#import "Recipe.h"

@interface minuteMealsDetailViewController ()

@end

@implementation minuteMealsDetailViewController

@synthesize recipePhoto;
@synthesize prepTimeLabel;
@synthesize ingredientTextView;
@synthesize recipeLabel;
@synthesize recipeName;
@synthesize recipe;
@synthesize instructionTextView;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];


    self.title = recipe.name;
    self.prepTimeLabel.text = recipe.prepTime;
    self.recipePhoto.image = [UIImage imageNamed:recipe.imageFile];

    NSMutableString *ingredientText = [NSMutableString string];
    for (NSString* ingredient in recipe.ingredients) {
        [ingredientText appendFormat:@"%@\n", ingredient];
    }
    self.ingredientTextView.text = ingredientText;

    self.instructionTextView.text = recipe.instructions;

    recipeLabel.text = recipeName;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showInstructions"]) {

        minuteMealsDetailViewController *destViewController = segue.destinationViewController;

        destViewController.instructionTextView.text = [recipe instructions];

    }
    NSLog(@"showInstructions Seque is being passed");
}


/*- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showRecipeDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];

        minuteMealsDetailViewController *destViewController = segue.destinationViewController;

        destViewController.recipe = [recipes objectAtIndex:indexPath.row];
    }
    NSLog(@"showRecipeDetial Segue is being passed");
}*/

- (void)viewDidUnload
{
    [self setRecipePhoto:nil];
    [self setPrepTimeLabel:nil];
    [self setIngredientTextView:nil];
    [self setInstructionTextView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

//
//  Recipe.h
//  minuteMeals
//
//  Created by KMO on 8/19/12.
//  Copyright (c) 2012 KAM Digital. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Recipe : NSObject

@property (nonatomic, strong) NSString *name; // name of recipe
@property (nonatomic, strong) NSString *prepTime; // preparation time
@property (nonatomic, strong) NSString *imageFile; // image filename of recipe
@property (nonatomic, strong) NSArray *ingredients; // ingredients
@property (nonatomic, strong) NSString *instructions; // instruction set

@end

//
//  Recipe.m
//  minuteMeals
//
//  Created by KMO on 8/19/12.
//  Copyright (c) 2012 KAM Digital. All rights reserved.
//

#import "Recipe.h"

@implementation Recipe

@synthesize name;
@synthesize prepTime;
@synthesize imageFile;
@synthesize ingredients;
@synthesize instructions;

@end

【问题讨论】:

  • 糟糕,忘了提我正在使用一个按钮将 recipeDetailViewController 连接到 recipeInstructionsViewController。此代码将 recipeInstructionsViewController 显示为 recipeDetailViewController 的一个类。我之前将它作为自己的课程,但没有解决它应该拥有的原因。

标签: iphone ios storyboard segue recipe


【解决方案1】:

尝试先将指令设置为自己的属性,并在viewDidLoad中设置标签

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showInstructions"]) {

        minuteMealsDetailViewController *destViewController = segue.destinationViewController;

        destViewController.instructionText = [recipe instructions];

    }
    NSLog(@"showInstructions Seque is being passed");
}

instructionText 是一个新属性。

并在 viewDidLoad 中为您的说明ViewController 做

instructionTextView.text = self.instructionText;

编辑:

您看不到任何东西的原因是视图没有完全加载到prepareForSegue 中,所有视图的初始化都应该在viewDidLoad 中。当可以安全地更改视图时调用该方法。

您现在对“recipeDetail”和“instructions”使用相同的视图控制器 我建议为您提供一个单独的 viewController 类。

只需将您的指令作为该 viewController 中的属性传递。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showInstructions"]) {

        MinuteMealsInstructionsViewController *destViewController = segue.destinationViewController;

        destViewController.instructionText = [recipe instructions];

    }
    NSLog(@"showInstructions Seque is being passed");
}

其中MinuteMealsInstructionsViewController 是具有指令属性的新类。

您说您希望将配方保留在配方对象中。这仍然是正确的,因为您只传递对对象成员的引用。假设您更改了说明字符串,那么它也会在您的配方对象中更改,因为该字符串只是一个参考。

附带说明:根据 Objective-c 样式指南,您应该使用以大写字母开头的类名。

如果您真的想在同一个 viewController 中执行此操作,您可以简单地将整个配方对象 destViewController.recipe = recipe; 和 viewDidLoad 传递:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.instructionTextLabel = recipe.instructions;
}

【讨论】:

  • 我可以这样做,但我的属性已经在配方对象中列出。除了名称、准备时间和配料外,我还有这些说明作为我的食谱类型的属性。所有其他数据都通过 segue 传递给 recipeDetailViewController 就好了,但是当我想将指令传递给 recipeInstructionsViewController 时,什么都没有传递。我想尽可能多地使用对象,而不为每个 segue 定义一堆字符串数组。我希望这是可能的,但也许 Xcode 不能做到这一点?
  • Okej,现在我明白你做了什么。 minuteMealsDetailViewController 实例中的destinationViewController(与实例化它的视图控制器类相同)。这真的是你想要的吗?我用另一种解决方案编辑了我的答案。
  • 是的,在这个项目的再现中,我为两个视图控制器使用了相同的类。我有一个单独的类,但在所有这些不同的类之间传递数据证明很麻烦。我想如果我将视图控制器保持在同一个类中,那么 instructionsViewController 上的指令文本视图(UITextView)将只是 recipeDetailViewController 的扩展。最初的教程不是为此而设计的,也许我应该从头开始。我在其他地方读到我应该将数据加载到 .plist 文件中,但我没有在这里这样做。
  • 我不确定你在追求什么,但这听起来像是一个过于复杂的设计。为您的指令创建一个单独的类,并将其连接到界面构建器中的视图,并按照我上面的描述进行操作,您应该在家安全。为此,您不需要将数据存储在 .plist 中。仅当您希望它持久存在但在这种情况下(存储配方)您应该正确使用核心数据或其他一些数据库解决方案。如果您对我的回答感到满意,请勾选复选框接受它:)
猜你喜欢
  • 1970-01-01
  • 2015-11-16
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多