OGeek|极客世界-中国程序员成长平台

标题: core-data - 如何序列化 NSPredicate 对象? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:32
标题: core-data - 如何序列化 NSPredicate 对象?

有没有办法检查 NSPredicate 对象以将其序列化为 URL?我正在尝试远程检索数据,并且需要将谓词对象转换为带有服务器可以理解的查询字符串参数的 URL。

这受到了 WWDC 2010 上一场名为“构建服务器驱动的用户体验”的演讲的启发,演讲者在演讲中谈到了使用 Core-Data 和服务器后端。我已经关注了 session 视频和幻灯片,但被困在序列化点上。例如,有一个 Person 对象,我试图获取所有名字为“John”的人。我正在使用一个名为 RemoteManagedObjectContextNSManagedObjectContext 子类,它覆盖了 executeFetchRequest 方法,并且应该将调用发送到服务器。提取请求被创建为(省略的非必要部分):

@implementation PeopleViewController

- (NSArray *)getPeople {
    RemoteFetchRequest *fetchRequest = [[RemoteFetchRequest alloc] init];
    NSEntityDescription *entity = ...
    NSPredicate *template = [NSPredicate predicateWithFormat:
                                @"name == $NAME AND endpoint = $ENDPOINT"];
    NSPredicate *predicate = [template predicateWithSubstitutionVariables:...];

    [fetchRequest setEntity:entity];
    [fetchRequest setPredicate:predicate];

    NSError *error = nil;
    // the custom subclass of NSManagedObjectContext executes this
    return [remoteMOC executeFetchRequest:fetchRequest error:&error];
}

@end

现在在 NSManagedObjectContext 的自定义子类中,如何将获取请求序列化为适合服务器的查询字符串参数。所以给定上面的 fetch 请求,对应的 URL 是:

http://example.com/people?name=John

可以获得返回的谓词的字符串表示,

name == "John" AND endpoint == "people"

我可以解析得到参数 nameendpoint。但是,是否可以在不解析字符串的情况下做到这一点?这是 RemoteManagedObjectContext 类的部分实现。

@implementation RemoteManagedObjectContext

- (NSArray *)executeFetchRequestNSFetchRequest *)request errorNSError **)error {
    // this gives name == "John" AND endpoint == "people"
    // don't know how else to retrieve the predicate data
    NSLog(@"%@", [[request predicate] predicateFormat]);

    ...
}

@end



Best Answer-推荐答案


甚至比字符串表示更好的是面向对象的表示!而且它是自动完成的!

首先,检查 NSPredicate 的类。它将是一个 NSCompoundPredicate。将其转换为适当的变量。

然后您会看到它的 compoundPredicateTypeNSAndPredicateType,正如您所期望的那样。

还可以看到-subpredicates返回的数组揭示了2个NSComparisonPredicates

第一个子谓词有一个NSKeyPathExpressionType类型的左表达式和一个@"name"-keyPath,操作符是 NSEqualToPredicateOperatorType。正确的表达式将是 NSConstantValueExpressionType 类型的 NSExpression,而 -constantValue 将是 @"John"

第二个子谓词类似,除了左边表达式的 keyPath 将是 @"endpoint",而右边表达式的 constantValue 将成为@"people"

如果您想更深入地了解如何将 NSPredicates 转换为 HTTP Get 请求,请查看我的 StackOverflow framework, "StackKit" ,它就是这样做的。它基本上是一个行为类似于 CoreData 的框架,但使用 StackOverflow.com(或任何其他堆栈交换站点)来检索信息。在下面,它正在执行 lotNSPredicate 对象转换为 URL。如果您有任何具体问题,也欢迎您给我发电子邮件。

关于core-data - 如何序列化 NSPredicate 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4119642/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4