在视图控制器之间移动对象

时间:2014-07-16 17:44:24

标签: ios segue

我是编程新手,我遇到了将对象从一个VC移动到另一个VC的问题。

我的第二个VC有NSArray * objects。第三个VC有NSMutableArray *个产品。我有来自2的模态segue - > 3 这是我的segue方法:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:@"Products segue"]) {
     ProductsViewController*pvc = segue.destinationViewController;
     pvc.products = [self.objects mutableCopy];
}

}

ProductsViewController我创建了一些对象:

-(IBAction)addSomeObjects {
products = [NSMutableArray new];
[products addObject:@"Cola"];
[products addObject:@"Pepsi"];
[products addObject:@"Fanta"];
[products addObject:@"Red bull"];
[products addObject:@"Monster"];

如果我NSLog我的IBAction方法产品成功添加了我的对象但是当我dissmissViewController时我的对象数组是空的。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

微米。 Koptak。欢迎来到编程。

在此示例中,我建议您创建一个模型来管理产品。模型是表示数据的类。在此示例中,创建一个类来表示产品集合。为此,我将其称为目录。

// In Catalog.h
@interface Catalog : NSObject
@property (nonatomic, readonly) NSMutableArray *products;
@end

// In Catalog.m
@implementation Catalog
- (id)init
{
    self = [super init];
    if (self) {
        _products = [NSMutableArray array];
    }
}
@end

现在我有一个可以管理产品的类,我需要在第一个视图控制器和catalog中拥有Catalog属性(类型为ProductsViewController)。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"Products segue"]) {
        ProductsViewController *pvc = segue.destinationViewController;
        pvc.catalog = self.catalog; // Pass the catalog between the view controllers.
    }
}

- (void)viewDidLoad
{
    …
    if (self.catalog == nil) // Make sure an instance of `Catalog` has been created!
        self.catalog = [[Catalog alloc] init];
    …
}

最后,在ProductsViewController

-  (IBAction)addSomeObjects
{
    [self.catalog.products addObject:@"Cola"];
    [self.catalog.products addObject:@"Pepsi"];
    [self.catalog.products addObject:@"Fanta"];
    [self.catalog.products addObject:@"Red bull"];
    [self.catalog.products addObject:@"Monster"];
}

现在当您解雇ProductsViewController时,第一个视图控制器将拥有所有新产品。

注意:这是如何共享数据的第一步。它会跳过正确的类名,数据保护和数据验证,但它可以帮助您入门。

相关问题