首页 > 系统 > iOS > 正文

iOS 字典按照key的排序

2019-11-09 14:34:34
字体:
来源:转载
供稿:网友

方法一

-(NSString*)stringWithDict:(NSDictionary*)dict{        NSArray*keys = [dict allKeys];        NSArray*sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1,id obj2) {        return[obj1 compare:obj2 options:NSNumericSearch];//正序    }];        NSString*str =@"";        for(NSString*categoryId in sortedArray) {                id value = [dict objectForKey:categoryId];                if([value isKindOfClass:[NSDictionary class]]) {                        value = [self stringWithDict:value];                    }                if([str length] !=0) {                        str = [str stringByAppendingString:@","];                    }                str = [str stringByAppendingFormat:@"%@:%@",categoryId,value];            }    NSLog(@"str:%@",str);    return str;}方法二

-(NSString *)getNeedSignStrFrom:(id)obj{    NSDictionary *dict = obj;    NSArray *arrPRimary = dict.allKeys;        NSArray *arrKey = [arrPrimary sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){        NSComparisonResult result = [obj1 compare:obj2];        return result==NSOrderedDescending;//NSOrderedAscending 倒序    }];        NSString*str =@"";        for (NSString *s in arrKey) {        id value = dict[s];        if([value isKindOfClass:[NSDictionary class]]) {            value = [self getNeedSignStrFrom:value];        }        if([str length] !=0) {                        str = [str stringByAppendingString:@","];                    }                str = [str stringByAppendingFormat:@"%@:%@",s,value];            }    NSLog(@"str:%@",str);        return str;}

方法一是网上的

http://www.jianshu.com/p/753a6fd85a80

主要是排序的方式略有不同 运用递归的方法感觉挺好的


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表