核心数据中的谓词和组合过滤器?
Predicates and combined filters in core data?
我目前没有使用 Core Data,但我打算从 Realm 切换到它,如果我确定某个东西可以工作,这对我的应用程序当前的工作方式至关重要。我有一个包含两个对象的模型:
Message:
date - NSDate
text - String
images - One-to-many > Image
Image:
imageURL - String
message - Many-to-one > Image
我有一个显示图像和消息的 table 视图。当 UITableView 想知道时,我需要知道应该在某个索引路径上做什么。所以我需要能够执行类似于以下的查询:
"Give me an ordered list of images and messages, messages sorted by their date
and images sorted by their message.date
".
我该怎么做?
据我所知,您无法在核心数据提取请求期间对包含消息和图像的混合数组进行排序。这是一种可能的方法:
- 分别获取消息和图片
- 将两个数组合并为一个
- 排序唯一的一个数组
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context
函数
NSInteger sort(id item1, id item2, void *context) {
int v1 = [item1 iskindofClass[message class]]?item1.data:item1.message.date;
int v2 = [item2 iskindofClass[message class]]?item1.data:item1.message.date;
if (v1 < v2)
return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}
我目前没有使用 Core Data,但我打算从 Realm 切换到它,如果我确定某个东西可以工作,这对我的应用程序当前的工作方式至关重要。我有一个包含两个对象的模型:
Message:
date - NSDate
text - String
images - One-to-many > Image
Image:
imageURL - String
message - Many-to-one > Image
我有一个显示图像和消息的 table 视图。当 UITableView 想知道时,我需要知道应该在某个索引路径上做什么。所以我需要能够执行类似于以下的查询:
"Give me an ordered list of images and messages, messages sorted by their date
and images sorted by their message.date
".
我该怎么做?
据我所知,您无法在核心数据提取请求期间对包含消息和图像的混合数组进行排序。这是一种可能的方法:
- 分别获取消息和图片
- 将两个数组合并为一个
- 排序唯一的一个数组
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context
函数
NSInteger sort(id item1, id item2, void *context) {
int v1 = [item1 iskindofClass[message class]]?item1.data:item1.message.date;
int v2 = [item2 iskindofClass[message class]]?item1.data:item1.message.date;
if (v1 < v2)
return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}