如何访问NSMutableDictionary的键?

时间:2009-07-16 18:49:53

标签: iphone key nsdictionary nsmutabledictionary

NSMutableDictionary *bookmarks = [NSMutableDictionary dictionary];

[bookmarks setObject:[NSURL URLWithString:(NSString *) @"http://stanford.edu"] forKey:
@"Stanford University"];
[bookmarks setObject:[NSURL URLWithString:(NSString *) @"http://apple.com"] forKey:
@"Apple"];
[bookmarks setObject:[NSURL URLWithString:(NSString *) @"http://itunes.stanford.edu"] forKey:
@"Stanford on iTunesU"];
[bookmarks setObject:[NSURL URLWithString:(NSString *) @"http://stanfordshop.com"] forKey:
@"Stanford Mall"];

NSEnumerator *browser = [bookmarks keyEnumerator];
id each;
NSURL *url;
while ((each = [browser nextObject])) {
url = [bookmarks objectForKey:(NSString *)each];
NSLog('%@'", url);

我意识到斯坦福大学的iPhone编程已被打败(我敢肯定)。我只是在找出如何使用URL打印密钥时遇到一些麻烦。我也无法弄清楚如何只打印以斯坦福开头的钥匙。我知道这是NSString的一种方法。

2 个答案:

答案 0 :(得分:3)

for (NSString * key in [bookmarks allKeys])
{
  if ([key hasPrefix:@"Stanford"])
  {
    NSLog(key);
  }
}

答案 1 :(得分:0)

在某些情况下,使用'传递测试'系列方法可以最清楚地完成过滤集合,尽管在这种简单的情况下它看起来更复杂。

NSArray *keys = [bookmarks allKeys];
NSArray *stanfordKeys = [keys objectsAtIndexes:[keys indexesOfObjectsPassingTest:^BOOL(NSString *key, NSUInteger idx, BOOL *stop) {
    return [key hasPrefix:@"Stanford"];
}]];
NSLog(@"%@", stanfordKeys);