gpt4 book ai didi

Objective-C : Sorting NSMutableArray containing NSMutableArrays

转载 作者:太空狗 更新时间:2023-10-30 03:40:21 25 4
gpt4 key购买 nike

我目前在我的开发中使用 NSMutableArrays 来存储从 HTTP Servlet 中获取的一些数据。

一切都很好,因为现在我必须对数组中的内容进行排序。

这就是我所做的:

NSMutableArray *array = [[NSMutableArray arrayWithObjects:nil] retain];
[array addObject:[NSArray arrayWithObjects: "Label 1", 1, nil]];
[array addObject:[NSArray arrayWithObjects: "Label 2", 4, nil]];
[array addObject:[NSArray arrayWithObjects: "Label 3", 2, nil]];
[array addObject:[NSArray arrayWithObjects: "Label 4", 6, nil]];
[array addObject:[NSArray arrayWithObjects: "Label 5", 0, nil]];

第一列包含一个标签,第二列是一个分数,我希望数组按降序排列。

我存储数据的方式好吗?有没有比在 NSMutableArray 中使用 NSMutableArrays 更好的方法?

我是 iPhone 开发新手,我看过一些关于排序的代码,但感觉不太好。

预先感谢您的回答!

最佳答案

如果您要创建自定义对象(或至少使用 NSDictionary)来存储信息,而不是使用数组,这会容易得多。

例如:

//ScoreRecord.h
@interface ScoreRecord : NSObject {
NSString * label;
NSUInteger score;
}
@property (nonatomic, retain) NSString * label;
@property (nonatomic) NSUInteger score;
@end

//ScoreRecord.m
#import "ScoreRecord.h"
@implementation ScoreRecord
@synthesize label, score;

- (void) dealloc {
[label release];
[super dealloc];
}

@end

//elsewhere:
NSMutableArray * scores = [[NSMutableArray alloc] init];
ScoreRecord * first = [[ScoreRecord alloc] init];
[first setLabel:@"Label 1"];
[first setScore:1];
[scores addObject:first];
[first release];
//...etc for the rest of your scores

填充完 scores 数组后,您现在可以:

//the "key" is the *name* of the @property as a string.  So you can also sort by @"label" if you'd like
NSSortDescriptor * sortByScore = [NSSortDescriptor sortDescriptorWithKey:@"score" ascending:YES];
[scores sortUsingDescriptors:[NSArray arrayWithObject:sortByScore]];

在此之后,您的 scores 数组将按分数升序排序。

关于 Objective-C : Sorting NSMutableArray containing NSMutableArrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2766994/

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