gpt4 book ai didi

ios - 在 View Controller 之间移动对象

转载 作者:行者123 更新时间:2023-11-29 02:48:49 25 4
gpt4 key购买 nike

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

我的第二个 VC 有 NSArray * 对象。第三个 VC 有 NSMutableArray *产品。我有 2 -> 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 时,我的对象数组是空的。

感谢您的帮助。

最佳答案

米。科普塔克。欢迎编程。

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

// 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

现在我有了一个可以管理产品的类,我需要在第一个 View Controller 和 ProductsViewController 中都有 catalog 属性(Catalog 类型)

- (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 时,第一个 View Controller 将拥有所有新产品。

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

关于ios - 在 View Controller 之间移动对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24787340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com