0

Baiscally 我想用核心数据查询的结果更新 UILabel。我有一个带有以下文本的 UILabel “root has X credits”。我想在核心数据中搜索实体“帐户”,然后细化搜索以查找“根”帐户,然后细化搜索“根”帐户中的属性“信用”。最后,我想更新 UILabel 以读取“root has 0 credits”(或者 Core Data 查询描述的许多学分。

到目前为止,我有以下代码,

- (void)rootCreditAmount {
// Core Data - root credit amount
NSFetchRequest *request = [[NSFetchRequest alloc] init];

// define our table / entity to use
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Account" inManagedObjectContext:_managedObjectContext];
[request setEntity:entity];

// filter results to just root user
NSPredicate *username = [NSPredicate predicateWithFormat:@"root"];

[request setPredicate:username];

// fetch records and handle error
NSError *error;
NSMutableArray *mutableFetchResults = [[_managedObjectContext executeFetchRequest:request error:& error] mutableCopy];

if (!mutableFetchResults) {
    // handle error.
    // should advise user to restart
}
NSLog(@"mutablefetchresults = %@",mutableFetchResults);
}

不用说,这段代码目前正在导致我的应用程序崩溃。

4

2 回答 2

2

将您的谓词语句更改为:

[NSPredicate predicateWithFormat:@"username == root"];

将“用户名”更改为您的字段名称。有关格式化谓词字符串的更多信息,请参见此处

于 2012-07-09T02:56:35.467 回答
0

好吧,感谢@skytz 在chat.stackoverflow.com 的帮助,我能够做我需要的事情。我最终没有使用 NSPredicate。下面的方法最终解决了我的问题。但本着做一个好人的精神,我将把功劳归功于@melsam 的守时。

- (void)rootCreditAmount {
// Core Data - root credit amount
NSFetchRequest *request = [[NSFetchRequest alloc] init];

// define our table / entity to use
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Account" inManagedObjectContext:_managedObjectContext];
[request setEntity:entity];

// fetch records and handle error
NSError *error;
NSMutableArray *mutableFetchResults = [[_managedObjectContext executeFetchRequest:request error:&error] mutableCopy];

if (!mutableFetchResults) {
    // handle error.
    // should advise user to restart
}

// refine to just root account
for (Account *anAccount in mutableFetchResults) {
    if ([anAccount.username isEqualToString:@"root"]) {

        NSLog(@"root credit = %@",anAccount.credit);

        _lblRootCredit.text = [NSString stringWithFormat:@"root has %@ credits.",anAccount.credit];
    }
}
}
于 2012-07-09T03:35:28.987 回答