我有两个视图,我的第一个视图是 class1.m,第二个视图是 class2.m。当在第一个视图的工具栏上按下按钮时,我的第二个视图被初始化为弹出框。我的第二个视图中有一个数组,如果按下任何行,就会在其中添加对象。我试图在我的第一个视图中设置一个 KVO,以便我可以在我的第一个视图中从第二个视图访问 allSelectedFocus 数组,但它不起作用。我意识到我没有调用 removeObserver,但我不知道在哪里调用它,而不是在使用之前删除观察者。如果有人知道任何更好的方法来做到这一点,我愿意接受建议,但如果有人能让这个工作,那也太棒了。
//class2.m
#import "class2.h"
#import "class1.h"
@implementation class2
@synthesize selectedFocus = _selectedFocus;
@synthesize focusArray = _focusArray;
@synthesize allSelectedFocus = _allSelectedFocus;
- (void)viewDidLoad
{
_focusArray = [[NSArray alloc]initWithObjects:@"Balance",@"Bevægelse",@"Elementskift",@"Vejrtrækning",@"Alle",nil];
[super viewDidLoad];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return _focusArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSString *cellValue = [_focusArray objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
_selectedFocus = [[_focusArray objectAtIndex:indexPath.row] stringByAppendingString:@","];
if(![[self mutableAllSelectedFocus] containsObject:_selectedFocus])
{
//add object to array, if it's not already there
[[self mutableAllSelectedFocus] addObject:_selectedFocus];
}
else
{
//remove object from array, if it's already there
[[self mutableAllSelectedFocus] removeObject:_selectedFocus];
}
}
-(NSMutableArray *)allSelectedFocus
{
if(_allSelectedFocus == nil)
{
_allSelectedFocus = [[NSMutableArray alloc]init];
}
return _allSelectedFocus;
}
-(NSMutableArray *)mutableAllSelectedFocus
{
return [self mutableArrayValueForKey:@"allSelectedFocus"];
}
@end
//class1.m
#import "class1.h"
#import "class2.h"
@implementation class1
- (void)viewDidLoad
{
[super viewDidLoad];
if(_focusTag == nil)
{
_focusTag = [[class2 alloc]init];
}
[_focusTag addObserver:self forKeyPath:@"selectedFocus" 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]);
}
}