gpt4 book ai didi

iphone - 对二维数组进行排序

转载 作者:行者123 更新时间:2023-11-28 18:44:42 26 4
gpt4 key购买 nike

我有以下情况。我从 xml 提要和 facebook graph api 导入数据,在本例中是帖子。我想将这些数据合并到一个数组中,并根据包含的日期数据对其进行排序。

我现在有以下内容:

[containerArray addObject: [NSMutableArray arrayWithObjects: created_time, message, picture, fbSource, nil ]
];

这将创建一个二维数组,但我想对 created_time 上的所有条目进行排序。

我怎样才能最好地解决这个问题?提前谢谢!!

最佳答案

创建一个包含必要实例变量而不是可变数组的数据类。然后你可以使用 NSArray 类的各种排序方法,例如 sortedArrayUsingDescriptors .

排序可能是这样的:

NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"created_time" 
ascending:YES] autorelease];

NSArray *sortedArray = [containerArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

[sortDescriptor release];

编辑

引用 Fowler 先生的书 Refactoring: Improving the Design of Existing Code .

Replace Array with Object

You have an array in which certain elements mean different things.

Replace the array with an object that has a field for each element

...

Motivation

Arrays are a common structure for organizing data. However, they should be used only to contain a collection of similar objects in somre order.

这就是我们想要在这里做的。让我们创建一个简单的 Posts 类。您可以轻松添加接受四个值作为参数的自定义初始化程序,甚至可以添加一个方便的类方法来稍后返回一个自动释放的对象。这只是一个基本框架:

后.h

@interface Posts : NSObject 
{
NSDate *created_time;
NSString *message;
UIImage *picture;
id fbSource; // Don't know what type :)
}

@property (nonatomic, retain) NSDate *created_time;
@property (nonatomic, copy) NSString *message;
@property (nonatomic, retain) UIImage *picture;
@property (nonatomic, retain) id fbSource;

@end

后.m

#import "Post.h"

@implementation Post

@synthesize created_time, message, picture, fbSource;

#pragma mark -
#pragma mark memory management

- (void)dealloc
{
[created_time release];
[message release];
[picture release];
[fbSource release];
[super dealloc];
}

#pragma mark -
#pragma mark initialization

- (id)init
{
self = [super init];
if (self) {
// do your initialization here
}
return self;
}

编辑 2

将 Post 对象添加到您的数组:

Post *newPost = [[Post alloc] init];
newPost.reated_time = [Date date];
newPost.message = @"a message";
newPost.picture = [UIImage imageNamed:@"mypic.jpg"];
// newPost.fbSource = ???
[containerArray addObject:newPost];

[newPost release];

关于iphone - 对二维数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6056242/

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