iOS开发 - Coredata


#pragma Mark - 获取上下文
+(NSManagedObjectContext *)getContext{
    return [(AppDelegate *)[UIApplication sharedApplication].delegate managedObjectContext];
}

#pragma Mark - 增
+(void)insertDataWithName:(NSString *)name andPassword:(NSString *)password andImage:(NSData *)image{

    User * user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:[CoreDataManager getContext]];

    user.name = name;
    user.password = password;
    user.headimage = image;

    NSError * error;
    if ([[CoreDataManager getContext] save:nil]) {
        NSLog(@"存储成功");
    }else{
        NSLog(@"存储失败 %@",error);
    }
}

#pragma Mark - 查
+(NSArray *)fetchData{

    NSFetchRequest * fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"User"];
    NSError * error;
    NSArray * arr =[[CoreDataManager getContext] executeFetchRequest:fetchRequest error:&error];
    if (error) {
        NSLog(@"%@",error);
        return nil;
    }else{
        return arr;
    }
}

#pragma Mark - 改
+(void)updateDataWith:(NSString *)pass{

    NSFetchRequest * fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"User"];
    NSError * error;
    NSArray *dataArr = [[CoreDataManager getContext] executeFetchRequest:fetchRequest error:&error];
    if (error) {
        NSLog(@"%@",error);
    }else{
        for (User * user in dataArr) {
            user.password = pass;
        }
    }
    [[CoreDataManager getContext] save:nil];
}

#pragma Mark - 删
+(void)deleteDataWith:(User *)user{

    [[CoreDataManager getContext] deleteObject:user];
    NSError * error;
    if ([[CoreDataManager getContext] save:&error]) {
        NSLog(@"删除成功");
    }else{
        NSLog(@"错误信息 %@",error);
    }
    [[CoreDataManager getContext] save:nil];
}

你可能感兴趣的:(iOS开发 - Coredata)