一直在用FMDB,不想再写sql语句了,所以改投coredata
建了两个实体类,friend、user
在coredata中进行下图的操作来自动生成model
然后就是对数据完成增删改查
//增加数据
AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
for (int i = 0; i < 10; i ++)
{
User *tmpUser = (User *)[NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([User class]) inManagedObjectContext:app.managedObjectContext];
NSString *username = [NSString stringWithFormat:@"%d",i];
NSString *password = [NSString stringWithFormat:@"a%d",i];
[tmpUser setUsername:username];
[tmpUser setPassword:password];
NSError *error = nil;
BOOL saveResult = [app.managedObjectContext save:&error];
if (saveResult)
{
NSLog(@"用户保存成功");
}
else
{
NSLog(@"用户保存失败");
}
Friend *tmpFriend = (Friend *)[NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Friend class]) inManagedObjectContext:app.managedObjectContext];
NSString *friendName = [NSString stringWithFormat:@"2%d",i];
NSString *firendAge = [NSString stringWithFormat:@"b%d",i];
NSString *friendRelation = username;
[tmpFriend setFriendName:friendName];
[tmpFriend setFriendAge:firendAge];
[tmpFriend setFriendRelation:friendRelation];
BOOL friendResult = [app.managedObjectContext save:&error];
if (friendResult)
{
NSLog(@"朋友保存成功");
}
else
{
NSLog(@"朋友保存失败");
}
}
//查找数据
NSFetchRequest *request = [[NSFetchRequest alloc] init];
//选表
NSEntityDescription *userDescription = [NSEntityDescription entityForName:NSStringFromClass([User class]) inManagedObjectContext:app.managedObjectContext];
[request setEntity:userDescription];
//查询条件
NSPredicate *userPredicate = [NSPredicate predicateWithFormat:@"username like %@",@"0"];
[request setPredicate:userPredicate];
NSError *error = nil;
NSMutableArray *userResultArray = [[app.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
for (int i = 0; i <userResultArray.count; i ++)
{
NSLog(@"%@",[userResultArray objectAtIndex:i]);
}
//修改数据
for (User *tmp in userResultArray)
{
[tmp setUsername:@"e"];
}
[app.managedObjectContext save:&error];
//删除数据
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *userDescription = [NSEntityDescription entityForName:NSStringFromClass([User class]) inManagedObjectContext:app.managedObjectContext];
[request setEntity:userDescription];
NSPredicate *userPredicate = [NSPredicate predicateWithFormat:@"username == 3"];
[request setPredicate:userPredicate];
NSError *error = nil;
NSMutableArray *userArray = [[app.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
for (User *tmp in userArray)
{
[app.managedObjectContext deleteObject:tmp];
}
[app.managedObjectContext save:&error]; //先把数据查出来,然后逐一删除,最后做一次保存数据,what the fuck?!apple 竟然这么复杂?!