Jos*_*Jos 0 arrays iphone objective-c ios
我有以下情况.我从xml feed和facebook graph api导入数据,在这种情况下是帖子.我想将这些数据合并到一个数组中,并对包含的日期数据进行排序.
我现在有以下内容:
[containerArray addObject: [NSMutableArray arrayWithObjects: created_time, message, picture, fbSource, nil ]
];
Run Code Online (Sandbox Code Playgroud)
这会创建一个二维数组,但我想在created_time上订购所有条目.
我怎样才能最好地解决这个问题?Thnx提前!!
创建一个包含必要实例变量而不是可变数组的数据类.然后,您可以使用NSArray类的各种排序方法sortedArrayUsingDescriptors.
排序可能如下所示:
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"created_time"
ascending:YES] autorelease];
NSArray *sortedArray = [containerArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
Run Code Online (Sandbox Code Playgroud)
编辑
引用福勒先生的书" 重构:改进现有规范的设计".
用对象替换数组
你有一个数组,其中某些元素意味着不同的东西.
将数组替换为具有每个元素的字段的对象
...
动机
数组是组织数据的常见结构.但是,它们应仅用于按照somre顺序包含类似对象的集合.
这就是我们想要做的.让我们创建一个简单的Posts类.您可以轻松添加自定义初始值设定项,它接受四个值作为参数,或者甚至是一个便捷类方法,以便稍后返回自动释放的对象.这只是一个基本的骨架:
@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
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)
编辑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];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
799 次 |
| 最近记录: |