gpt4 book ai didi

objective-c - NSMutableArray 返回 NULL

转载 作者:行者123 更新时间:2023-11-28 18:14:16 26 4
gpt4 key购买 nike

我尝试从另一个类 (secondViewController) 添加对象到 NSMutableArray,然后将它添加到我的 FirstViewController 中的 UITableView,但是当我使用 NSLog 打印它时它返回 null。这是我的设置。

FirstViewController.h:

@interface FirstViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>{
IBOutlet UITableView *mytableview;
NSMutableArray *mytableinfo;
}
@property (nonatomic,retain) IBOutlet UITableView *mytableview;
@property (retain) IBOutlet NSMutableArray *mytableinfo;

FirstViewController.m

#import "FirstViewController.h"
#import "SecondViewController.h"
@synthesize mytableinfo,mytableview;
-(IBAction)addShift:(id)sender{
SecondViewController *secondViewController = [[SecondViewController alloc]init];
[self presentModalViewController:secondViewController animated:YES];
}
- (void)viewDidLoad
{
mytableinfo = [[NSMutableArray alloc]init];
[super viewDidLoad];
}

SecondViewController.m

#import "SecondViewController.h"
#import "FirstViewController.h"

@implementation SecondViewController
@synthesize dateformatter,mydatepicker,startingTime;

-(IBAction)saveShift:(id)sender{
FirstViewController *firstViewController = [[FirstViewController alloc]init];
[firstViewController.mytableinfo addObject:@"Hello world"];
NSLog(@"%@",firstViewController.mytableinfo);
[self dismissModalViewControllerAnimated:YES];
}

我的目标是最终从 mytableinfo 提供一个 mytableview。我什至不确定这是否是最好的方法。任何建议将不胜感激。

最佳答案

在 SecondViewController 中,您正在使用 alloc init 创建 FirstViewController。那时,FirstViewController 上的 mytableinfo 为 nil,因为您直到 viewDidLoad 才进行分配。

什么加载了 SecondViewController?因为你模态地解雇了它。如果它是 FirstViewController,那么当您分配 init 第一个 View Controller 时,您不会调用以模态方式呈现它的实例。

让一个 View 像那样戳另一个 View 也不是很 MVC。它创建在 View 层耦合并在 View 层修改数据的代码。最好创建一个模型并让两个 View 修改该模型。

How to create a NSMutable Array which can access from different view controllers

View 之间通信的另一种方法是一个 View 将委托(delegate)(回调)传递给另一个 View 。这允许另一个 View 不耦合到另一个 View - 它只知道委托(delegate)的协议(protocol)。

What exactly does delegate do in xcode ios project?

关于objective-c - NSMutableArray 返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8004170/

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