核心数据筛选单个属性的结果,并设置UILabel的文本

时间:2012-07-09 02:34:21

标签: ios xcode core-data

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

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

- (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);
}

毋庸置疑,此代码导致我的应用程序暂时崩溃。

2 个答案:

答案 0 :(得分:2)

将谓词语句更改为:

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

将“用户名”更改为您的字段名称。有关格式化谓词字符串的详细信息,请See here

答案 1 :(得分:0)

非常感谢chat.stackoverflow.com中@skytz的帮助,我能够做我需要的事情。我最终没有使用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];
    }
}
}