我正在尝试从与创建它的不同的现有类访问 NSMutableArray。但如果我 NSLog 它,我会得到空值。我的程序在 class2 中启动,然后我转到 class1,通过按一行或多行创建我的 NSMutableArray,然后我希望我的 class2 获取更新的 NSMutableArray 实例,但它得到的只是空值。下面的代码:
//class1.m
#import "FocusTagTableViewController.h"
#import "STATableViewController.h"
@implementation FocusTagTableViewController
@synthesize focusArray = _focusArray;
@synthesize allSelectedFocus = _allSelectedFocus;
- (void)viewDidLoad
{
_focusArray = [[NSArray alloc]initWithObjects:@"Balance",@"Bevægelse",@"Elementskift",@"Vejrtrækning",@"Alle",nil];
[super viewDidLoad];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *selectedFocus = [[_focusArray objectAtIndex:indexPath.row] stringByAppendingString:@","];
if(_allSelectedFocus == nil)
{
_allSelectedFocus = [[NSMutableArray alloc]init];
[_allSelectedFocus addObject:selectedFocus];
}
else if(![_allSelectedFocus containsObject:selectedFocus])
{
[_allSelectedFocus addObject:selectedFocus];
}
}
//class2.m
#import "STATableViewController.h"
#import "FocusTagTableViewController.h"
@implementation STATableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
FocusTagTableViewController *focusTag = [[FocusTagTableViewController alloc]init];
[focustag addObserver:self forKeyPath:@"allSelectedFocus" options:NSKeyValueObservingOptionNew context:NULL];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"allSelectedFocus"])
{
NSLog(@"%@", [object valueForKeyPath:keyPath]);
}
}