【问题标题】:ios and coredata: NSPredicate does not work on fetch requestios 和 coredata:NSPredicate 不适用于获取请求
【发布时间】:2011-11-10 01:13:09
【问题描述】:

我有以下课程

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>


@interface Bankdaten : NSManagedObject

@property (nonatomic, retain) NSString * blz;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * https;

@end

和实现

#import "Bankdaten.h"

@implementation Bankdaten

@dynamic blz;
@dynamic name;
@dynamic https;

@end

我检查了这个对象的数据是否被核心数据正确保存在我的 sqlite 数据库的相应表中。

现在,我想通过执行此请求来获取特定对象:

-(Bankdaten*) ladeBankdaten:(NSString*) blz
{
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Bankdaten" inManagedObjectContext:moc];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(blz == '%@')", blz];
    [request setPredicate:predicate];

    NSError *error = nil;
    NSArray *array = [moc executeFetchRequest:request error:&error];
    if (array == nil) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    if( [array count] == 0 )
        return nil;
    return [array objectAtIndex:0];
}

问题:在这种情况下,数组总是包含零对象,因此我的方法返回 nil,尽管 blz 参数必须匹配数据库中的某个值。所以获取请求应该是肯定的。如果我评论该行

[request setPredicate:predicate];

如果没有为此请求设置谓词,则数据加载正常,因此我认为谓词在某种程度上被我错误地使用了。我在这里做错了什么?

【问题讨论】:

    标签: ios core-data fetch


    【解决方案1】:

    你的想法是正确的。改变这个:

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(blz == '%@')", blz];
    

    到:

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"blz == %@", blz];
    

    使用 NSPredicate,您不会在字符串参数周围使用单引号; predicateWithFormat 会自动处理这个问题。

    括号很好,但除非您正在执行需要它们的谓词逻辑,否则最好将它们排除在外并保持谓词尽可能简单。

    【讨论】:

    • 非常感谢您,挽救了我的 一些 头发被扯掉的问题 - 我还发现,例如,这在以前也有效:@"guid == '%@' ", itemId
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 2017-04-16
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    相关资源
    最近更新 更多