- 先按照网上的教程,建一个简单的带coredata的项目
- 再 添加一个 UserInfo 对象(表)(按照网上的教材,可视化方式添加)
- 然后在AppDelegate.m中按如下修改,(只添加了4个方法)
- 然后运行,看控制台日志
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- {
- self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
- // Override point for customization after application launch.
- self.window.backgroundColor = [UIColor whiteColor];
- [self.window makeKeyAndVisible];
- [self addUser];
- [self gainDatas];
- return YES;
- }
- //添加
- -(void)addUser{
- UserInfo * userInfo = [NSEntityDescription insertNewObjectForEntityForName:@"UserInfo"
- inManagedObjectContext:self.managedObjectContext];
- userInfo.name = @"dage";
- userInfo.password = @"password3";
- NSError *error = nil;
- if (![self.managedObjectContext save:&error]) {
- NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
- abort();
- }
- NSLog(@"add success");
- }
- //查询
- -(void)gainDatas {
- NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
- [fetchRequest setEntity:[NSEntityDescription entityForName:@"UserInfo" inManagedObjectContext:self.managedObjectContext]];
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like[cd]'baobao'"];//查询条件
- // NSPredicate *predicate = [NSPredicate predicateWithFormat:@"password='password3'"];//查询条件
- NSMutableArray *sortDescriptors = [NSMutableArray array]; //排序用
- [sortDescriptors addObject:[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] ]; //排序用
- [fetchRequest setPredicate:predicate]; //查询条件
- [fetchRequest setFetchBatchSize:5]; //分页
- [fetchRequest setSortDescriptors:sortDescriptors]; //排序
- [fetchRequest setReturnsObjectsAsFaults:NO];
- [fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"name", @"password", nil]]; //查询的字段,一般不需要
- NSError *error = nil;
- NSArray *fetchedItems = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
- if (fetchedItems == nil) {
- NSLog(@"fetch request resulted in an error %@, %@", error, [error userInfo]);
- }else {
- NSLog(@"fetchedItems=%d",fetchedItems.count);
- for (UserInfo *user in fetchedItems) {
- NSLog(@"user.authour=%@",user.name);
- // [self deleteUser:user]; //删除
- // [self updateUser:user]; //更新
- }
- }
- }
- //删除:NSManagedObject对象必须先取出来,用managedObjectContext删除,保存就好
- -(void)deleteUser:(id)user{
- [self.managedObjectContext deleteObject:user];
- NSError *error = nil;
- if (![self.managedObjectContext save:&error]) {
- NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
- abort();
- }
- NSLog(@"delete success");
- }
- //更新:直接修改对象,保存managedObjectContext就好
- -(void)updateUser:(UserInfo*)user{
- user.name = @"baobao"; //修改后,直接保存managedObjectContext就可以了
- NSError *error = nil;
- if (![self.managedObjectContext save:&error]) {
- NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
- abort();
- }
- NSLog(@"update success");
- }
转载于:https://www.cnblogs.com/zsw-1993/archive/2013/01/18/4880474.html