所以我有NSMutableArray
加载了对象my viewDidLoad
方法。为了检查,我将NSLog(@"%d", [self.myMutableArray count]);
放在viewDidLoad方法的末尾,得到了6。
当我将NSLog
放在tableView:didSelectRowAtIndexPath
等其他方法上时,我会得到相同的数字,6。
问题是当我从NSLog
方法调用相同的IBAction
时,我得到0.为什么?
此外,我真正想要做的是从另一个类访问此属性,但我得知它是空的:
HabitsTableViewController *habitsViewController = [[HabitsTableViewController alloc] initWithNibName:@"HabitsTableViewController" bundle:nil];
NSLog(@"%d",[habitsViewController.habits count]);
答案 0 :(得分:1)
这是因为您正在创建HabitsTableViewController
的新实例。您需要维护一个指向您想要影响的控制器的指针。
保持指向另一个类的指针的一种方法是,将其声明为属性。如果你需要它保留在这个类中,请使用strong;如果应该由另一个类保留,则使用weak。
在你的.h
@property (strong, nonatomic) HabitsTableViewController * pointerToHabitsTableViewController;
然后,在你的.m中,当你调用HabitsTableViewController时,将它分配给指针:
_pointerToHabitsTableViewController = ...;
然后,改变这个:
HabitsTableViewController *habitsViewController = [[HabitsTableViewController alloc] initWithNibName:@"HabitsTableViewController" bundle:nil];
NSLog(@"%d",[habitsViewController.habits count]);
To This:
NSLog(@"%d",[_pointerToHabitsTableViewController.habits count]);
答案 1 :(得分:0)
你HabitsTableViewController变量是release,为了防止发布必须保存NSMutablearray如果你计划在你的class.h中使用多个实例或者在变量HabitsTableViewController中