[英]add an object in my array each time I enter to the view
how can I add an object in my array each time I enter to my TableView I put this code in viewDidLoad and viewDidAppear methods but it seems to doesn't work : 每当我进入TableView时,如何在数组中添加对象,将这段代码放在viewDidLoad和viewDidAppear方法中,但似乎不起作用:
- (void)viewDidLoad
{
[super viewDidLoad];
if (!myArray) {
myArray = [[NSMutableArray alloc] init];
}
[peopleListe insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
NSLog(@"%@",myArray);
}
when I put this code in a button it works 当我将此代码放在按钮中时,它可以工作
Thank you for your help 谢谢您的帮助
viewDidLoad
is called once, when the view loads. 视图加载时,一次调用
viewDidLoad
。
viewWillAppear
is called every time you go into that view. 每当您进入该视图时,都会调用
viewWillAppear
。
If you want to do something each time a view appears, put the code in viewWillAppear
. 如果您希望每次出现视图时都执行某项操作,请将代码放入
viewWillAppear
。
EDIT: It's possible that your array is getting dealloc'd. 编辑:很有可能您的数组正在dealloc'd。 Try setting a breakpoint in
dealloc
as a simple way to see if that's the case: 尝试在
dealloc
设置断点,以查看是否是这种情况的简单方法:
- (void)dealloc {
NSLog(@"BYE!); // <-- put your breakpoint here
}
If it is, you'll have to (a) store your data somewhere else, or (b) keep this view/controller from being dealloced. 如果是这样,您将必须(a)将数据存储在其他位置,或者(b)防止该视图/控制器被取消分配。
Also, who is your tableViewDelegate
? 另外,谁是您的
tableViewDelegate
? That will have to implement methods returning the number of items in the table view and so on. 那将必须实现返回表视图中项目数的方法,依此类推。 I recommend having a read through the docs to get all those relationships sorted out.
我建议您通读文档,以弄清所有这些关系。
You don't want to have that array as a property/ivar of your view controller. 您不想将该数组作为视图控制器的属性/ ivar。 The view controller may, and will, get deallocated when it's not used (eg if it's inside the navigation controller, and you tap the "back" button to go to the previous screen.) When the view controller gets deallocated, your array obviously ceases to exist.
当不使用视图控制器时,它可能会并且将被释放(例如,如果它在导航控制器中,并且您单击“后退”按钮以转到上一个屏幕。)当视图控制器被释放时,您的数组显然会停止存在。
I suggest creating keeping that array in a separate place, eg in a singleton data object, or even (as a quick short-term solution) your app delegate. 我建议创建将该数组放置在单独的位置,例如,放置在一个单例数据对象中,或者甚至将其作为应用程序委托(作为快速的短期解决方案)。
About the code you posted: keep in mind that [UIViewController viewDidLoad]
is only called once during the view controller's lifecycle. 关于您发布的代码:请记住,
[UIViewController viewDidLoad]
在视图控制器的生命周期中仅被调用一次。 It may get called more than once, but that would mean that the original instance has been dealloc'd (and your original array is gone). 它可能会被调用多次,但这意味着原始实例已被解除分配(原始数组已消失)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.