字典里面的排序
{
NSDictionary * numsDic = @{@(2):@"second",
@(1):@"first",
@(3):@"thrid"};
NSDictionary * strDic = @{@"mark_1":@"first",
@"mark_3":@"thrid",
@"mark_2":@"second"};
//针对的是NSString类型的value,@selector(compare:)其实是调用的NSString里面的方法,所以在此不用实现,不过可以在NSSting的分类中重写,用于测试使用。
NSArray * numsSortedKeys = [numsDic keysSortedByValueUsingSelector:@selector(compare:)];
NSArray * strSortedKyes = [strDic keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSString * str1 = obj1;
NSString * str2 = obj2;
return [str1 compare:str2];
}];
NSLog(@"%@",numsSortedKeys.description);
NSLog(@"%@",strSortedKyes.description);
}
字典里的过滤
NSDictionary * numsDic = @{@(2):@"second",
@(1):@"first",
@(3):@"thrid"};
NSSet * filteredKyes = [numsDic keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) {
BOOL result = NO;
NSNumber * numKey = key;
if (numKey.integerValue > 2) {
result = YES;
}
return result;
}];
NSLog(@"%@",filteredKyes.description); //结果时key值:3
//这是一个很好的对字典进行过滤的方法,返回keys的集合,这些keys符合参数block的约束,在block内部在特定的条件下返回yes,返回的这个集合会保留当前遍历到那个字典对象的信息
// - (NSSet *)keysOfEntriesPassingTest:(BOOL (^)(id key, id obj, BOOL *stop))predicate NS_AVAILABLE(10_6, 4_0);
objectsForKeys:notFoundMarker:示例:没有对应的value的时候设置特定的mark.
{
NSArray *keyArr = @[@"k1", @"k2", @"k3"];
NSArray *objArr = [NSArray arrayWithObjects:@"v1", @"v2", @"v3", nil];
NSArray *srcArr = [NSArray arrayWithObjects:@"k0", @"k2", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:objArr forKeys:keyArr];
// NSArray *resArr = [dict objectsForKeys:srcArr notFoundMarker:@"not found"]; // ("not found", v2)
NSArray *resArr = [dict objectsForKeys:srcArr notFoundMarker:[NSNull null]]; // ("<null>", v2)
NSLog(@"%@",resArr); //结果:("<null>", v2)
}
针对url的参数解析成字典
NSString* wxNASAURLPath = @"http://weixin.sogou.com/weixin?type=2&ie=utf-8&query=NASA%E5%8F%91%E7%8E%B0%E6%96%B0%E5%9C%B0%E7%90%83";
NSURLComponents* wxNASAURLComponents = [NSURLComponents componentsWithString:wxNASAURLPath];
NSMutableDictionary* queryItemDict = [NSMutableDictionary dictionary];
NSArray* queryItems = wxNASAURLComponents.queryItems;
for (NSURLQueryItem* item in queryItems) {
[queryItemDict setObject:item.value forKey:item.name];
}
NSLog(@"queryItemDict = %@", queryItemDict);
}