我在使用谓词从核心数据存储中获取结果时遇到问题。我的应用程序所做的是根据一个或多个谓词从存储中获取结果,并向您显示基于所有谓词的结果或基于每个谓词的结果。
它在大多数情况下都工作得很好,除了我不能让“小于”查询工作。下面是我使用的代码:
case CriteriaSelectionIsLessThan:
pred = [NSPredicate predicateWithFormat:@"ANY value.attribute.name == %@ AND ANY value.%@ < %@", [attribute name], keyPath, [[activeValue value] value]];
break;
case CriteriaSelectionIsMoreThan:
pred = [NSPredicate predicateWithFormat:@"ANY value.attribute.name == %@ AND ANY value.%@ > %@", [attribute name], keyPath, [[activeValue value] value]];
break;
'more‘谓词的代码运行良好,它返回查询的数据集,比如> 1970 (一年)。当我尝试使用“小于”谓词对其进行筛选时,例如< 1970,它将返回整个核心数据数据集(未经过筛选)。
[activeValue value值]是一个NSNumber。
我怎么也搞不懂--谓词是完全一样的,只是有一个字符不同!
我们将非常感谢您的帮助。如果您需要更多代码/信息,请让我知道。
编辑:下面是我从JSON导入时映射数据类型的方式:
[attrib setDataType:[NSNumber numberWithInteger:[[attribute valueForKey:@"type"] integerValue]]];...
// Set the correct data type of the value
switch ([[attrib dataType] integerValue]) {
case AttributeDataTypeNumber:
[value setNumberValue:[NSNumber numberWithInteger:[valueForKey integerValue]]];
break;
case AttributeDataTypeString:
[value setStringValue:(NSString *)valueForKey];
break;
case AttributeDataTypeDate: {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"dd-MM-YYYY"];
[value setDateValue:[df dateFromString:(NSString *)valueForKey]];
}
break;
case AttributeDataTypeBool:
[value setBooleanValue:[NSNumber numberWithBool:[valueForKey boolValue]]];
break;
}
看,我的JSON中的数据类型保证是正确的,因为我在导入它之前进行了检查(而不是在应用程序中)。即使我构建了一个显式声明我想要某个枚举的谓词(比如value.attribute.dataType == 1,1是枚举中的一个数字),它仍然不起作用。这真的很奇怪。
发布于 2012-10-10 22:31:45
我想通了!如果其他人遇到了这个问题,下面是我如何解决它的:
[NSPredicate predicateWithFormat:@"SUBQUERY(value, $val, $val.attribute.name == %@ && $val.%@ < %@).@count > 0", [attribute name], keyPath, [[activeValue value] value]]
我认为这是因为它是一个多对多的键,必须在多个标准上进行匹配。当我使用ANY关键字时,我认为这是返回我不想要的值的罪魁祸首。现在工作起来像个护身符。
发布于 2012-10-05 07:40:33
您确定它返回的是整个数据集吗?我将猜测您为lessThan操作获取的值是具有value.%@
空值的对象
编辑:
下面是我如何动态处理模型的属性:
for (NSEntityDescription *entity in [self.managedObjectModel entities]) // self.managedObjectModel is a NSManagedObjectModel
{
for (NSAttributeDescription *attribute in [[entity attributesByName] allValues])
{
NSString *key = [attribute name];
// do something with key
switch ([attribute attributeType])
{
case NSBooleanAttributeType:
case NSInteger16AttributeType:
case NSInteger32AttributeType:
case NSInteger64AttributeType:
case NSDecimalAttributeType:
case NSDoubleAttributeType:
case NSFloatAttributeType:
// do something with numeric types
break;
case NSStringAttributeType:
// do something with string types
break;
case NSDateAttributeType:
// do something with date types
break;
}
}
}
每个case
处理谓词的方式各不相同。您可以缓存key:type关系以提高性能。
https://stackoverflow.com/questions/12740125
复制相似问题