核心数据。使用常量文字作为属性名称的NSPredicate问题 [英] Core data. NSPredicate issue using constant literals as names of properties

查看:126
本文介绍了核心数据。使用常量文字作为属性名称的NSPredicate问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 NSManagedObject 的属性。假设一个属性是:

I have NSManagedObject with properties. Suppose that one property it is:

@property (retain, nonatomic) NSString *city;

对于从核心数据获取数据,我总是使用 NSPredicate 。谓词如下所示:

For fetching data form core data I always use NSPredicate. The predicate looks like below:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %@", @"city", @"San Francisco"];

但是这里的问题是,项目使用键city作为未定义的键,所以让我们假设我在我的应用程序中使用键城市1000次,所以然后我需要替换所有这些键与新的一个NSManagedObject的属性改变,例如。到cityName。在这种情况下,我需要使用谓词:

But the problem here that the project use key "city" as undefined key in meaning like a constant. So lets suppose that I use key "city" in my app 1000 times, so then I need to replace all this keys with new one if property of NSManagedObject was changed, e.g. to cityName. In this case I need to use predicate:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %@", @"cityName", @"San Francisco"];

这不舒服。所以现在我使用全局 extern NSString key kCity = @city; 但是如果数据模型改变也有一个问题,因为如果属性将更改我将崩溃只有当运行应用程序和控制台会说我:

It is not comfortable. So right now I am using global extern NSString key kCity = @"city"; but in case if the data model changed as well there is a problem, because if property will be changed I will have crash only when run app and console will say me:

'key path city not found in entity <NSSQLEntity...

哪种解决方法可以在这里?我想使用像

Which workaround can be here? I thought using something like

NSString * const kCity = myEntity.city.propertyString;

所以如果属性改变了,解析器会告诉我项目有错误, app。所以,在我改变属性为常数只有那么我将能够运行app

So if property was changed then parser will tell me that project has an error and I can't run app. So after I change property for constant only then I will be able to run app

如何获得属性的名称在NSString。

How can get name of property in NSString. Of course it is just suggestion and maybe someone have another variant.

感谢

推荐答案

您可以使用 mogenerator ,其中一件事是创建一个 struct 用于可以使用的属性和关系键。

You could use mogenerator, one thing it does is to create a struct for attribute and relationship keys that you can use.

// .h
extern const struct MBListAttributes {
    __unsafe_unretained NSString *title;
} MBListAttributes;

// .m
const struct MBListAttributes MBListAttributes = {
    .title = @"title",
};

然后,您可以使用 MBListAttributes.title 获得正确的密钥。

You can then use MBListAttributes.title to get the correct key.

这篇关于核心数据。使用常量文字作为属性名称的NSPredicate问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆