使用CoreData [1]
本篇教程能教你从无开始接触CoreData,包括新建工程,创建出实体,增删改查样样都有,属于使用CoreData最初级教程.
1. 创建带有CoreData的工程项目
2. 添加一个实体类
3. 创建出实体类
4. 创建对象,保存对象,执行代码
以下是验证结果:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSLog(@"%@", NSHomeDirectory());
// 实体描述信息
NSEntityDescription *description = \
[NSEntityDescription entityForName:@"Student"
inManagedObjectContext:[self managedObjectContext]];
// 初始化对象
Student *student = [[Student alloc] initWithEntity:description
insertIntoManagedObjectContext:[self managedObjectContext]];
student.name = @"YouXianMing";
student.age = [NSNumber numberWithInt:26];
// 保存对象
[self saveContext];
return YES;
}
这样就实现了存储对象.
5. 重复上面的步骤存储5个对象.
6. 遍历出所有的对象
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// 设定要查询的实体
NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
// 取出查询结果
NSArray *students = [[self managedObjectContext] executeFetchRequest:fetch error:nil];
// 遍历
[students enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Student *student = obj;
NSLog(@"%@ %@", student.age, student.name);
}];
return YES;
}
7. 删除一个对象
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// 设定要查询的实体
NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
// 取出查询结果
NSArray *students = [[self managedObjectContext] executeFetchRequest:fetch error:nil];
// 遍历
[students enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Student *student = obj;
// 找到匹配的数据,删除之
if ([student.name isEqualToString:@"QiuLiang"])
{
[[self managedObjectContext] deleteObject:student];
}
}];
// 存储
[self saveContext];
// 遍历
[students enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Student *student = obj;
NSLog(@"%@ %@", student.age, student.name);
}];
return YES;
}
8. 修改一个对象
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// 设定要查询的实体
NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
// 取出查询结果
NSArray *students = [[self managedObjectContext] executeFetchRequest:fetch error:nil];
// 遍历
[students enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Student *student = obj;
// 找到匹配的数据,修改之
if ([student.name isEqualToString:@"YouXianMing"])
{
student.age = [NSNumber numberWithInt:100];
}
}];
// 存储
[self saveContext];
// 遍历
[students enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Student *student = obj;
NSLog(@"%@ %@", student.age, student.name);
}];
return YES;
}
9. 根据谓词查找出实体的方法请自行百度脑补,这里不赘述了.
时间: 2024-09-07 22:26:40