我是iOS开发中的新手。我的数组包含字典值键,如
for(NSDictionary *dict in self.imageArray )
{
[self.imagesa addObject:@{@"demopage":[dict valueForKey:@"demopage"]}];
}
这里我的“demoPage”键值包含两个键,如“link”和“Pageno”,此处链接包含我的ImageURL,“pageno”包含页码,如
-demopage
{
link:"URL",
page_no: "12"
},
{
link:"URL",
page_no: "13"
},
{
link: "URL",
page_no: "14"
},
{
link: "",
page_no: "3"
},
{
link:"URL",
page_no: "31"
},
{
link: "URL",
page_no: "32"
},
当我解析它然后我得到数据在这个范围像12,13,14,3,31,32我想安排这个图像像页码我希望它像1,2,3至数据阵列。
答案 0 :(得分:4)
出于某种原因,您将页码存储为字符串而不是数字。因此,简单的排序将按字母顺序排序。
即。 1,10,11,12,2,20,21,235,3,35,4
你需要它按字面数字排序,你可以这样做......
NSSortDescriptor *alphaNumSD = [NSSortDescriptor sortDescriptorWithKey:@"page_no" ascending:YES comparator:^(NSString *string1, NSString *string2) {
return [string1 compare:string2 options:NSNumericSearch];
}];
NSArray *sortedArray = [self.theArrayYouWantToSort sortedArrayUsingDescriptors:@[alphaNumSD]];
NSArray *originalArray = @[
@{@"page_no": @"27"},
@{@"page_no": @"1"},
@{@"page_no": @"12"},
@{@"page_no": @"23"},
@{@"page_no": @"3"},
@{@"page_no": @"2"},
@{@"page_no": @"17"},
];
NSSortDescriptor *alphaNumSD = [NSSortDescriptor sortDescriptorWithKey:@"page_no"
ascending:YES
comparator:^(NSString *string1, NSString *string2)
{
return [string1 compare:string2 options:NSNumericSearch];
}];
NSArray *sortedArray = [originalArray sortedArrayUsingDescriptors:@[alphaNumSD]];
NSLog(@"%@", sortedArray);
(
{
"page_no" = 1;
},
{
"page_no" = 2;
},
{
"page_no" = 3;
},
{
"page_no" = 12;
},
{
"page_no" = 17;
},
{
"page_no" = 23;
},
{
"page_no" = 27;
}
)
它绝对有效。
答案 1 :(得分:0)
NSArray *ordersArray = info[@"result"];
NSArray *properSortedArray = [ordersArray sortedArrayUsingComparator:
^(id obj1, id obj2)
{
NSInteger value1 = [[obj1 objectForKey: @"orderId"] intValue];
NSInteger value2 = [[obj2 objectForKey: @"orderId"] intValue];
if (value1 > value2)
{
return (NSComparisonResult)NSOrderedAscending;
}
if (value1 < value2)
{
return (NSComparisonResult)NSOrderedDescending;
}
return (NSComparisonResult)NSOrderedSame;
}];
答案 2 :(得分:-2)
尝试:
[self.dataArray sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"page_no" ascending:YES]]]