首页 > 其他 > 详细

CoreData的学习记录(2)

时间:2014-03-20 18:29:38      阅读:538      评论:0      收藏:0      [点我收藏+]

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

CoreData的学习记录(2)

原文:http://blog.csdn.net/ioswyl88219/article/details/21631603

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!