gpt4 book ai didi

objective-c - NSUSerDefaults 与 NSMutableArray 按 desc 顺序排序

转载 作者:行者123 更新时间:2023-11-29 04:13:09 26 4
gpt4 key购买 nike

我很困惑为什么降序排序不适用于以下代码。我想通过前 5 名分数和其他逻辑来限制。分数将如下所示:22/30、12/18、34/38、23/32 等。我添加/删除了 SortDescriptor 以按降序排序,它似乎适用于前 3 个项目,但随后无法正确排序。有人可以帮忙吗?

- (NSMutableArray*) method1:(NSString *) mode byScore: (NSString *) score
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *array = [[defaults objectForKey:mode]mutableCopy];

if (!array)
{
array = [[NSMutableArray alloc] init];
}
NSLog(@"The content of array is%@", array);

if ([array count] < 5)
{
if (![array containsObject:score])
{
[array addObject:score];
// Need to sort here. But not too sure this is the right place
NSLog(@"The content of the sorted array upto 5 is%@", array);
}
}
else
{
if (![array containsObject:score])
{
if ([array lastObject] < score)
{
[array addObject:score];
// Need to sort here before I remove the last object
[array removeLastObject];
NSLog(@"The content of the sorted array else is%@",array);
}
}
}
[defaults setObject:array forKey:mode];
[defaults synchronize];
// I want the array in NSUserDefaults to be sorted in desc order
// don't know what to return here ==> the array object or the defaults object cast to NSMutableArray?
}

最佳答案

辅助函数

static NSComparisonResult CompareFloats( float a, float b )
{
if ( a < b ) { return NSOrderedAscending ; }
else if ( a > b ) { return NSOrderedDescending ; }
return NSOrderedSame ;
}

NSString 上的类别

@implementation NSString (Stuff)

-(float)floatValueForFraction
{
NSArray * components = [ self componentsSeparatedByString:@"/" ] ;
return [ components[0] floatValue ] / [ components[1] floatValue ] ;
}

@end

你的方法:

- (void)addScore:(NSString*)score forMode:(NSString*)mode
{
NSUserDefaults * defaults = [ NSUserDefaults standardUserDefaults ] ;
NSArray * scores = [ defaults objectForKey:mode ] ;

scores = scores ? [ scores arrayByAddingObject:score ] : @[ score ] ;
scores = [ scores sortedArrayUsingComparator:^(NSString * a, NSString * b){
return CompareFloats( [ a floatValueForFraction ], [ b floatValueForFraction ] ) ;
}]

if ( scores.count > 5 ) { scores = [ scores subarrayWithRange:(NSRange){ .length = 5 } ] ; }

[ default setObject:scores forKey:mode ] ;
}

如果您想在调用此方法后更新高分,只需使用 [ [ NSUserDefaults standardUserDefaults ] objectForKey:<mode> ] .最好让你的方法只做一件事。

关于objective-c - NSUSerDefaults 与 NSMutableArray 按 desc 顺序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14088921/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com