1.判断是不是重复创建的方法
- (BOOL)createTeamWithName:(NSString *)teamName city:(NSString *)teamCity
{
//不加判断的方法
// if (!teamName || !teamCity) {
// return NO;
// }
//
// Team *teamObject = [NSEntityDescription insertNewObjectForEntityForName:@"Team" inManagedObjectContext:self.managedObjectContext];
// teamObject.name = teamName;
// teamObject.city = teamCity;
//
// return YES;
if (!teamName || !teamCity) {
return NO;
}
Team *teamObject = [self getTeamInfoByName:teamName];
if (nil == teamObject) {
teamObject = [NSEntityDescription insertNewObjectForEntityForName:@"Team" inManagedObjectContext:self.managedObjectContext];
}
teamObject.name = teamName;
teamObject.city = teamCity;
return YES;
}
- (Team *)getTeamInfoByName:(NSString *)teamName
{
Team *teamObject = nil;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *teamEntity = [NSEntityDescription entityForName:@"Team" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:teamEntity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", teamName];
[fetchRequest setPredicate:predicate];
[fetchRequest setFetchLimit:1];
NSError *error = NULL;
NSArray *array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(@"Error : %@\n", [error localizedDescription]);
}
if (array && [array count] > 0) {
teamObject = [array objectAtIndex:0];
}
fetchRequest = nil;
return teamObject;
}
CoreData的学习记录(2),布布扣,bubuko.com
原文:http://blog.csdn.net/ioswyl88219/article/details/21631603