Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
All the code necessary to find a Category object by name in Objective C
#import <CoreData/CoreData.h>
#import "FindableData.h"
@interface Category : FindableData
{
}
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSSet *auctions;
@property (nonatomic, retain) NSNumber *auctionCount;
@end
@interface Category (CoreDataGeneratedAccessors)
+ (NSArray *)findByName:(NSString *)name fromContext:(NSManagedObjectContext *)context;
@end
#import "Category.h"
@implementation Category
@dynamic name;
@dynamic auctions;
@dynamic auctionCount;
+ (NSArray *)findByName:(NSString *)name fromContext:(NSManagedObjectContext *)context {
NSArray *fetchResults = nil;
NSPredicate *predicate = nil;
if (name != nil) {
predicate = [NSPredicate predicateWithFormat:@"name = %@",name];
}
fetchResults = [super findFromContext:context withEntity:@"Category" andPredicate:predicate];
return fetchResults;
}
@end
#import <CoreData/CoreData.h>
@interface FindableData : NSManagedObject {
}
+ (NSArray *)findFromContext:(NSManagedObjectContext *)context withEntity:(NSString *)entityName andPredicate:(NSPredicate *)pred;
+ (NSArray *)findFromContext:(NSManagedObjectContext *)context withEntity:(NSString *)entityName;
@end
#import "FindableData.h"
@implementation FindableData
+ (NSArray *)findFromContext:(NSManagedObjectContext *)context withEntity:(NSString *)entityName andPredicate:(NSPredicate *)pred {
NSError *fetchError = nil;
NSArray *fetchResults;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
[fetchRequest setEntity:entity];
if (pred != nil) [fetchRequest setPredicate:pred];
fetchResults = [context executeFetchRequest:fetchRequest error:&fetchError];
[fetchRequest release];
if (fetchResults != nil && ([fetchResults count] > 0) && fetchError == nil) {
return fetchResults;
}
if (fetchError != nil) {
NSLog(@"find error: %@", fetchError);
} else {
// Could not fetch any results; that's not really an error, though.
if(pred != nil) {
NSLog(@"No results searching for: %@", pred);
} else {
NSLog(@"No %@ data.", entityName);
}
}
return nil;
}
+ (NSArray *)findFromContext:(NSManagedObjectContext *)context withEntity:(NSString *)entityName {
return [FindableData findFromContext:context withEntity:entityName andPredicate:nil];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment