self.sections = [[NSMutableDictionary alloc] init];
BOOL found;
for (NSDictionary *wine in sortedWines)
{
NSNumber *rate = [wine valueForKey:@"Rate"];
NSString *rateStr = [NSString stringWithFormat:@"%.f", [rate floatValue]];
found = NO;
for (NSString *str in [self.sections allKeys])
{
if ([str isEqualToString:rateStr])
{
found = YES;
}
}
if (!found)
{[self.sections setValue:[[NSMutableArray alloc] init] forKey:rateStr];}
}
for (NSDictionary *wine in sortedWines)
{[[self.sections objectForKey:[NSString stringWithFormat:@"%.f", [[wine valueForKey:@"Rate"] floatValue]] ] addObject:wine];}
// Sort:
for (NSString *key in [self.sections allKeys])
{[[self.sections objectForKey:key] sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"Rate" ascending:NO]]];}
此代碼將我的葡萄酒放入部分,但不會按降序對它們進行排序!難道是因爲NSNumber被轉換成NSString?我試着使用NSNumber的價值做出代碼:嘗試按降序排列部分
self.sections = [[NSMutableDictionary alloc] init];
BOOL found;
for (NSDictionary *wine in sortedWines)
{
NSNumber *rate = [wine valueForKey:@"Rate"];
found = NO;
for (NSNumber *str in [self.sections allKeys])
{
if ([str isEqualToNumber:rate])
{
found = YES;
}
}
if (!found)
{[self.sections setValue:[[NSMutableArray alloc] init] forKey:rate];}
}
// Loop again to sort wines into their keys
for (NSDictionary *wine in sortedWines)
{[[self.sections objectForKey:[wine valueForKey:@"Rate"]] addObject:wine];}
// Sort each section array
for (NSString *key in [self.sections allKeys])
{[[self.sections objectForKey:key] sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"Rate" ascending:NO]]];}
但它給出了
if (!found)
{[self.sections setValue:[[NSMutableArray alloc] init] forKey:rate];}
一個警告,說「不兼容的指針類型發送的NSNumber ___strong到類型的NSString的參數」
如果我運行它與錯誤崩潰的應用程序-[__NSCFNumber localizedCaseInsensitiveCompare:]: unrecognized selector sent to instance 0x1e085810
我有什麼改變,使其工作和降序排序的部分?謝謝。
嗯,我想用你想要的方式使用NSSortDescriptors排序所有的鍵更好。只需按照您的標準對它們進行排序,然後按順序將對象從字典中取出。 – Sandeep
它看起來像第二種方法應該工作 - 我不明白任何錯誤。嘗試記錄[rate class]以確保它是一個NSNumber。你確定第一個錯誤出現在你認爲的線上嗎?至於第二個錯誤,我不知道caseInsensitiveCompare來自哪裏。你在哪裏設置的?我認爲該方法的選擇器只是比較:(並且它應該使用NSNumber的比較版本:如果你將它傳遞給一個NSNumber)。 – rdelmar