Xcode:基于NSDictionary从NSMutableArray中删除对象

时间:2012-07-28 20:56:38

标签: xcode nsmutablearray nsdictionary

我是tableViews和词典的新手,我遇到了问题! 在ViewDidLoad中,我正在初始化许多MutableArrays,我正在使用NSDictionary添加数据。例如:

- (void)viewDidLoad {
nomosXiou=[[NSMutableArray alloc] init];

[nomosXiou addObject:[[NSDictionary alloc] initWithObjectsAndKeys:@"Mary",@"name",@"USA",@"country", nil]];
[nomosXiou addObject:[[NSDictionary alloc] initWithObjectsAndKeys:@"Peter",@"name",@"Germany",@"country", nil]]; 

[super viewDidLoad];
// Do any additional setup after loading the view.}

在之前的ViewController中,用户选择国家/地区。基于该选择,我怎么能从我的数组中删除所有其他条目???

提前致谢...

2 个答案:

答案 0 :(得分:2)

首先请注意您的代码片段有错误。它应该是:

NSMutableArray *nomosXiou= [[NSMutableArray alloc] init];

有很多方法可以做你想要的,但最直接的可能是:

NSString *countryName;    // You picked this in another view controller
NSMutableArray *newNomosXiou= [[NSMutableArray alloc] init];

for (NSDictionary *entry in nomosXiou) {
    if ([[entry objectForKey:@"country"] isEqualToString:countryName])
        [newNomosXiou addObject:entry];
}

完成此操作后,newNomosXiou将仅包含来自nomosXiou中设置的国家/地区的countryName条目。

答案 1 :(得分:0)

这样的事情可以胜任:

NSMutableArray *nomosXiou = [[NSMutableArray alloc] init];
NSString *country = @"Germany"; // This is what you got from previous controller

// Some test data. Here we will eventually keep only countries == Germany
[nomosXiou addObject:[[NSDictionary alloc] initWithObjectsAndKeys:@"Mary",@"name",@"USA",@"country", nil]];
[nomosXiou addObject:[[NSDictionary alloc] initWithObjectsAndKeys:@"Peter",@"name",@"Germany",@"country", nil]];
[nomosXiou addObject:[[NSDictionary alloc] initWithObjectsAndKeys:@"George",@"name",@"Germany",@"country", nil]];

// Here we'll keep track of all the objects passing our test
// i.e. they are not equal to our 'country' string
NSIndexSet *indexset = [nomosXiou indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop){
    return (BOOL)![[obj valueForKey:@"country"] isEqualToString:country];
    }];

// Finally we remove the objects from our array
[nomosXiou removeObjectsAtIndexes:indexset];