2

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

这是受 WWDC 2010 中的一个名为“构建服务器驱动的用户体验”的演讲启发的,演讲者在演讲中谈到了使用 Core-Data 和服务器后端。我已经关注了会议视频和幻灯片,但被困在序列化点上。例如,有一个Person对象,我试图获取所有名字为“John”的人。我正在使用NSManagedObjectContext被调用的子类RemoteManagedObjectContext,它覆盖了该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,如何将获取请求序列化为适合服务器的查询字符串参数。因此,鉴于上述获取请求,相应的 URL 将是:

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

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

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

我可以解析以获取参数name,并且endpoint。但是,是否可以在不解析字符串的情况下做到这一点?RemoteManagedObjectContext这是该类的部分实现。

@implementation RemoteManagedObjectContext

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

    ...
}

@end
4

1 回答 1

4

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

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

然后你会看到它compoundPredicateTypeis NSAndPredicateType,就像你期望的那样。

您还可以看到-subpredicates显示 2返回的数组NSComparisonPredicates

第一个子谓词有一个左表达式类型NSKeyPathExpressionType和一个-keyPathof @"name",运算符是NSEqualToPredicateOperatorType。正确的表达式将是 anNSExpression类型NSConstantValueExpressionType,而 the-constantValue将是@"John"

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

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

于 2010-11-13T06:42:50.363 回答