查询Core Data属性的类型

时间:2011-11-18 01:20:28

标签: iphone ios core-data

我有一个如下所示的通用方法:

-(NSArray *) db_select: (NSString *) entity where: (NSString*) fieldKey equals: (NSString*) value withSortField: (NSString *) sortField withFetchLimits:(NSRange) fetchLimits{
// convert value to a number if it isn't a string
if (value != nil && ![value isKindOfClass:[NSString class]]){
    if ([value isKindOfClass:[NSNumber class]]){
        value = [((NSNumber*)value) stringValue];
    }
}

// assemble
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entity inManagedObjectContext:moContext];
if (fieldKey != nil){
    NSPredicate *predicate = [NSPredicate 
                              predicateWithFormat:@"%K like %@",
                              fieldKey,value];
    [request setPredicate:predicate];
}
[request setEntity:entity];
[request setFetchLimit:fetchLimits.length];
[request setFetchOffset:fetchLimits.location];

if (sortField != nil){
    NSSortDescriptor *sortDescriptor = nil;
               if (/*TODO fieldKey refers to an NSString */YES){
                         sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[self extractSortField:sortField] ascending:[self isAscending:sortField]  selector:@selector(localizedCaseInsensitiveCompare:)];
               } else {
                         sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[self extractSortField:sortField] ascending:[self isAscending:sortField]];
               }
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [request setSortDescriptors:sortDescriptors];
}

// make the request
NSError *error;
return [moContext executeFetchRequest:request error:&error];

}

如果字段(aka fieldKey)不是String,我想不要执行localizedCaseInsensitiveCompare。如何查询核心数据模式并确定entity.fieldKey是字符串还是其他?

三江源!

1 个答案:

答案 0 :(得分:1)

您可以通过其实体作为实例:

NSEntityDescription *desc = [myEntity entity];
NSAttributeDescription *attDesc = [[desc propertiesByName] valueForKey:@"myProperty"];
NSAttributeType *type = [attDesc attributeType];

从那里,一个简单的开关将决定你正在处理什么。