Mike S
Mike S

Reputation: 4122

Inquire on type of Core Data attribute

I have a generic method that looks like the following:

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

}

and I want to not do the localizedCaseInsensitiveCompare if the field (aka fieldKey) is not a String. How do I enquire of the core data schema and work out if the entity.fieldKey is a string or otherwise?

Thankyou!

Upvotes: 1

Views: 87

Answers (1)

Marcus S. Zarra
Marcus S. Zarra

Reputation: 46718

You can as an instance via its entity:

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

From there a simple switch will determine what you are dealing with.

Upvotes: 1

Related Questions