好的,我有点问错了,所以我编辑了原来的问题。
我在数组中存储数组,以及NSDictionaries。它是一种实用类型的应用程序,没有设置结构,用户可以根据需要输入嵌套信息。
理想情况下,我需要一个方法来给定一个set参数(一种类,可能是一个字典键)来滚动我的数组的整个内容。这是一个例子..
NSMutableArray *array = [[NSMutableArray alloc]init];
NSMutableDictionary *enteredItem = [[NSMutableDictionary alloc]init];
[enteredItem setObject:@"i'm a title" forKey:@"title"];
[enteredItem setObject:@"i'm an id" forKey:@"id"];
[enteredItem setObject:@"i'm a description" forKey:@"description"];
[enteredItem setObject:@"i'm a timestamp" forKey:@"timestamp"];
[enteredItem setObject:array forKey:@"items"];
[array addObject:enteredItem];
[array addObject:anotherDictionary];
[array addObject:moreDictionaries];
所以在上面的例子中,我需要找到包含@“我是id”的字典(并返回它)。
希望我的问题很明确。感谢您提供的任何帮助。
答案 0 :(得分:4)
递归方法是正确的,但如果您还不知道递归,我不确定代码示例是否非常有用。这是一个有效的解决方案:
添加以下方法:
- (id)findObjectWithKey:(id)key inArray:(NSArray *)array
{
for (id object in array)
{
if ([object isKindOfClass:[NSArray class]])
{
return [self findObjectWithKey:key inArray:object];
}
else if ([object isKindOfClass:[NSDictionary class]])
{
return [self findObjectWithKey:key inDictionary:object];
}
}
return nil;
}
- (id)findObjectWithKey:(id)key inDictionary:(NSDictionary *)dict
{
for (id subKey in dict)
{
id object = [dict objectForKey:subKey];
if ([subKey isEqual:key])
{
return object;
}
else if ([object isKindOfClass:[NSArray class]])
{
return [self findObjectWithKey:key inArray:object];
}
else if ([object isKindOfClass:[NSDictionary class]])
{
return [self findObjectWithKey:key inDictionary:object];
}
}
return nil;
}
然后找到你的对象,只需说:
id object = [self findObjectForKey:@"title" inArray:array];
要修改查找特定对象的方法并返回字典键,请改为:
- (id)findKeyWithObject:(id)key inArray:(NSArray *)array
{
for (id object in array)
{
if ([object isKindOfClass:[NSArray class]])
{
return [self findKeyWithObject:key inArray:object];
}
else if ([object isKindOfClass:[NSDictionary class]])
{
return [self findKeyWithObject:key inDictionary:object];
}
}
return nil;
}
- (id)findKeyWithObject:(id)object inDictionary:(NSDictionary *)dict
{
for (id key in dict)
{
id subObject = [dict objectForKey:key];
if ([subObject isEqual:object])
{
return key;
}
else if ([subObject isKindOfClass:[NSArray class]])
{
return [self findKeyWithObject:object inArray:object];
}
else if ([subObject isKindOfClass:[NSDictionary class]])
{
return [self findKeyWithObject:object inDictionary:object];
}
}
return nil;
}
然后找到你的钥匙,只需说:
id key = [self findKeyWithObject:object inArray:array];
答案 1 :(得分:1)
递归搜索怎么样?
- (void) searchRecursive :(NSArray *) array {
NSEnumerator *e = [array objectEnumerator];
id obj;
while ((obj = [e nextObject])) {
if ([e isKindOfClass [NSArray class]])
[self searchRecursive :obj]
else
objobject ... forKey ...
答案 2 :(得分:1)
正如ott所说,递归方法符合您的要求。您还需要检查字典是否包含您想要的键(因为我猜您可能有不同类型的对象由字典表示...)。也许您可以创建一个NSDictionary类别来检查它是否与字典类类型匹配。
我的意思是:
- (void)isType1
{
return (([self objectForKey:@"title"] != nil) && [self objectForKey:@"id"] != nil) && ...);
}
我知道它可能更“复杂”,但这可能很有用。