好的,我把问题分解成一个更容易理解的简单问题。所以下面的代码有一系列数字:1,0,1,0但是当我在它排序后将它打印出来时,它打印出来:0,0,0,0。我在这做错了什么?
SortedDetailFields * sorty = [[SortedDetailFields alloc]init];
NSMutableArray * fieldArray = [[NSMutableArray alloc]init];
BOOL fieldone, fieldtwo,fieldthree,fieldfour;
NSSortDescriptor *fff = [NSSortDescriptor sortDescriptorWithKey:@"numbersToSort"
ascending:NO];
fieldone = true;
fieldtwo = false;
fieldthree = true;
fieldfour = false;
if (fieldone) {
sorty.numbersToSort = @"1";
[fieldArray addObject:sorty];
}else{
sorty.numbersToSort = @"0";
[fieldArray addObject:sorty];
}
if (fieldtwo) {
sorty.numbersToSort = @"1";
[fieldArray addObject:sorty];
}else{
sorty.numbersToSort = @"0";
[fieldArray addObject:sorty];
}
if (fieldthree) {
sorty.numbersToSort = @"1";
[fieldArray addObject:sorty];
}else{
sorty.numbersToSort = @"0";
[fieldArray addObject:sorty];
}
if (fieldfour) {
sorty.numbersToSort = @"1";
[fieldArray addObject:sorty];
}else{
sorty.numbersToSort = @"0";
[fieldArray addObject:sorty];
}
NSLog(@"By numbers : %@",[fieldArray sortedArrayUsingDescriptors:@[fff]]);
for (SortedDetailFields * detain in fieldArray) {
NSLog(@"Number %@",detain.numbersToSort);
}
所以我的问题是如何排序和打印对象,使它们匹配序列1,1,0,0? 任何帮助是极大的赞赏。谢谢!
答案 0 :(得分:0)
以@Naveen Prasad R的评论为基础:
最简单的解决方案是创建NSDictionaries,每次都是新的:
NSMutableArray* fieldArray = [NSMutableArray new];
[fieldArray addObject:@{@"field":@"fieldOne",@"value":"@(fieldone)}];
[fieldArray addObject:@{@"field":@"fieldTwo",@"value":"@(fieldtwo)}];
[fieldArray addObject:@{@"field":@"fieldThree",@"value":"@(fieldthree)}];
[fieldArray addObject:@{@"field":@"fieldFour",@"value":"@(fieldfour)}];
NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:@"value"
ascending:NO];
NSArray* sortedArray = [fieldArray sortedArrayUsingDescriptors:@[sorter]];
for (NSDictionary* dict in sortedArray) {
NSLog(@"Number %@",dict[@"value"]);
}
这应该有效。另请确保如果您使用' sortedArrayUsingDescriptors
',您的原始数组将不会更改,但会返回已排序的版本! (在我的示例' sortedArray
')
而不是字符串' fieldOne',' fieldTwo' ......你应该只使用你的真实物体!