【问题标题】:Query Array In Objective C (Like MySQL)在 Objective C 中查询数组(如 MySQL)
【发布时间】:2012-07-04 08:00:04
【问题描述】:

所以基本上我有一个巨大的数组数组(只有一个二维数组)......

假设我的根数组有 100 个子数组...

我想查询根/子数组并只返回其 2 对象等于 hello 的子数组...

所以基本上我在下面有一个虚构的想法......

updatedArray = [rootArray WHERE childArray objectAtIndex:2 == @"hello"];

现在如您所见,我希望更新后的数组在 rootArray 中包含 40 或 50 个子数组...

明白我的意思 - 它有点像 MySQL,只使用数组而不是数据库?

【问题讨论】:

  • 顺便说一句,这与 MySQL 无关——这是一个通用的数据结构问题。而且数据库也是一种数据结构... :-)
  • 我去掉了 MySQL 和 C 标签,这两个标签肯定是不相关的。
  • @TheMan,阅读this question。我什至会说它可能是重复的。
  • 顺便说一句,第二个对象不在索引 2 处!显然,它在索引 1 处。
  • 这就是我在回答中写“第三个对象”的原因。

标签: iphone objective-c ios filter


【解决方案1】:

试试这个:

NSMutableArray *updated = [[NSMutableArray alloc] init];
for (NSArray *a in rootArray)
{
    if ([[a objectAtIndex:2] isEqualToString:@"hello"])
        [updated addObject:a];
}

现在updated 将包含rootArray 中的数组,其第三个对象是@"hello"

使用后别忘了释放它(如果你不使用 ARC)。

您还可以将谓词用于简单逻辑;见NSPredicate class.

【讨论】:

  • 这里用谓词肯定会更好?
【解决方案2】:

您可以使用NSPredicate 过滤您的数组,如下所示:

NSArray *data = [NSArray arrayWithObjects:
    [NSArray arrayWithObjects:@"One", @"Two", nil]
,   [NSArray arrayWithObjects:@"Three", @"Four", nil]
,   [NSArray arrayWithObjects:@"Nine", @"Two", nil]
,   nil];
NSPredicate *filter = [NSPredicate predicateWithBlock:^BOOL(id array, NSDictionary *bindings) {
    // This is the place where the condition is specified.
    // You can perform arbitrary testing on your nested arrays
    // to determine their eligibility:
    return [[array objectAtIndex:1] isEqual:@"Two"];
}];
NSArray *res = [data filteredArrayUsingPredicate:filter];
NSLog(@"%lu", res.count); 

【讨论】:

    猜你喜欢
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 2017-12-11
    • 1970-01-01
    • 2011-09-12
    相关资源
    最近更新 更多