ios coredata 增删改查代码

以Person实体为例(name、age、sex)
Person关系Tel(tel)
1增加数据

NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];  
        [person setValue:@"LiJunliang" forKey:@"name"];  
        [person setValue:[NSNumber numberWithInt:23] forKey:@"age"];  
        [person setValue:@"boy" forKey:@"sex"];  
        NSManagedObject *tel = [NSEntityDescription insertNewObjectForEntityForName:@"Tel" inManagedObjectContext:self.managedObjectContext];  
        [tel setValue:@"133xxxxyyyy" forKey:@"tel"];  
        [tel setValue:person forKey:@"owner"];  
        [person setValue:tel forKey:@"tel"];  
  
        if (![self.managedObjectContext save:&error]) {  
            NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);  
        }  

2删除数据

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];  
   NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];  
   [fetchRequest setEntity:entity];  
   NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];  
   for (NSManagedObject *info in fetchedObjects) {  
       [self.managedObjectContext deleteObject:info];  
   }  
     
   if ([self.managedObjectContext hasChanges]) {  
       [self.managedObjectContext save:&error];  
   }  

3修改数据

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];  
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"name == %@",@"xiaojie"]];  
    NSArray *fetchedObject = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];  
    for (NSManagedObject *info in fetchedObject) {  
        [info setValue:[NSNumber numberWithInt:24]forKey:@"age"];  
    }  
    if (![self.managedObjectContext save:&error]) {  
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);  
    }  

4查询数据

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];  
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"name == %@",@"xiaojie"]];  
    NSArray *fetchedObject = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];  
    for (NSManagedObject *info in fetchedObject) {  
        NSLog(@"Name :%@",[info valueForKey:@"name"]);  
        NSLog(@"Age :%@",[info valueForKey:@"age"]);  
        NSLog(@"Sex :%@",[info valueForKey:@"sex"]);  
    }  

PS:修改数据时现查询,如果实体查询出来的修改。最后保存时会更新,如果实体时新得到的会插入。

你可能感兴趣的:(ios coredata 增删改查代码)