开发者

Generic method that checks entity existence in Core Data database

I want to write generic method that checks if a given entity is in a Core Data database. I would like to have one method that works for all entities. I came up with something like this:

-(BOOL)checkIfExistsEntity:(NSString *)entityName withFieldName:(NSString *)fieldName andFieldValue:(NSString *)value{

    NSManagedObjectContext *managedObjectContext  = [(FGuideAppDelegate *) [[UIApplication sharedApplication] delegate] managedObjectContext];

    NSEntityDescription *selectEntityDescription = [NSEntityDescription
                                                    entityForName:entityName inManagedObjectContext:managedObjectContext];
    NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
   开发者_如何学Python [fetchRequest setEntity:selectEntityDescription];

    NSPredicate *whereForFetch = [NSPredicate predicateWithFormat:@"%@ = %@",fieldName, value];
    [fetchRequest setPredicate:whereForFetch];

    NSError *error = nil;
    NSArray *array = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (array != nil && [array count] > 0){
        return YES;
    }else {
        return NO;
    }
}

However it looks like the string @"%@ = %@" in the predicate I wrote is not parsed properly. Is there any way to implement described functionality without hardcoding entities properties in a predicate?


Check out dynamic property names in the link below. http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html

Instead of %@, using %K should solve your problem


you need == not = (I think....)


You could use the countForFetchRequest method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜