2011-11-18 35 views
1

我有一個看起來像下面這樣的通用方法:來電諮詢型核心數據屬性的

-(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]; 

}

,我想不是做localizedCaseInsensitiveCompare如果字段(又名fieldKey)不一個字符串。如何查詢核心數據模式,並確定entity.fieldKey是字符串還是其他字符?

謝謝!

回答

1

您可以根據通過其的實體實例:

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

從那裏,一個簡單的開關,將決定你正在處理。