CoreData的学习记录

1.如果想创建一个带有coreData的程序,要在项目初始化的时候勾选中


2.创建完成之后,会发现在AppDelegate里多出了几个属性,和2个方法



@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;

managedObjectContext (被管理的数据上下文)操作实际内容(操作持久层)作用:插入数据,查询数据,删除数据

NSManagedObjectModel(被管理的数据模型)数据库所有表格或数据结构,包含各实体的定义信息 作用:添加实体的属性,建立属性之间的关系操作方法:视图编辑器,或代码

NSPersistentStoreCoordinator(持久化存储助理)相当于数据库的连接器 作用:设置数据存储的名字,位置,存储方式,和存储时机

方法saveContext表示:保存数据到持久层(数据库)

方法applicationDocumentsDirectory表示:应用程序沙箱下的Documents目录路径


3.如果想创建一个实体对象的话,需要点击.xcdatamodel,Add Entity,添加想要的字段



4.生成对象文件,command+n,然后选中CoreData里的NSManagerObjectSubClass进行关联,选中实体创建


5.添加数据


Person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
    
    if (newPerson == nil){
        NSLog(@"Failed to create the new person.");
        return NO;
    }
    
    newPerson.firstName = paramFirstName;
    newPerson.lastName = paramLastName;
    newPerson.age = [NSNumber numberWithUnsignedInteger:paramAge];
    NSError *savingError = nil;
    
    if ([self.managedObjectContext save:&savingError]){
        return YES;
    } else {
        NSLog(@"Failed to save the new person. Error = %@", savingError);
    }

NSEntityDescription(实体结构)相当于表格结构



6.取出数据查询


/* Create the fetch request first */
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    /* Here is the entity whose contents we want to read */
    NSEntityDescription *entity =
    [NSEntityDescription
     entityForName:@"Person"
     inManagedObjectContext:self.managedObjectContext];
    /* Tell the request that we want to read the
     contents of the Person entity */
    [fetchRequest setEntity:entity];
    NSError *requestError = nil;
    /* And execute the fetch request on the context */
    NSArray *persons =
    [self.managedObjectContext executeFetchRequest:fetchRequest
                                             error:&requestError];
    /* Make sure we get the array */
    if ([persons count] > 0){
        /* Go through the persons array one by one */
        NSUInteger counter = 1;
        for (Person *thisPerson in persons){
            NSLog(@"Person %lu First Name = %@",
                  (unsigned long)counter, 
                  thisPerson.firstName); 
            NSLog(@"Person %lu Last Name = %@", 
                  (unsigned long)counter, 
                  thisPerson.lastName);
            NSLog(@"Person %lu Age = %ld",
                  (unsigned long)counter,
                  (unsigned long)[thisPerson.age unsignedIntegerValue]);
            counter++;
        }
    } else {
        NSLog(@"Could not find any Person entities in the context."); 
    }

7.删除数据


/* Create the fetch request first */
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    /* Here is the entity whose contents we want to read */
    NSEntityDescription *entity =
    [NSEntityDescription
     entityForName:@"Person"
     inManagedObjectContext:self.managedObjectContext];
    /* Tell the request that we want to read the
     contents of the Person entity */
    [fetchRequest setEntity:entity];
    NSError *requestError = nil;
    /* And execute the fetch request on the context */
    NSArray *persons =
    [self.managedObjectContext executeFetchRequest:fetchRequest
                                             error:&requestError];
    if ([persons count] > 0){
        /* Delete the last person in the array */
        Person *lastPerson = [persons lastObject];
        [self.managedObjectContext deleteObject:lastPerson];
        NSError *savingError = nil;
        if ([self.managedObjectContext save:&savingError]){
            NSLog(@"Successfully deleted the last person in the array.");
        } else {
            NSLog(@"Failed to delete the last person in the array.");
        }
    } else { 
        NSLog(@"Could not find any Person entities in the context."); 
    } 

8.排序


//排序
    NSSortDescriptor *ageSort = [[NSSortDescriptor alloc]initWithKey:@"age" ascending:YES];
    NSSortDescriptor *firstNameSort =
    [[NSSortDescriptor alloc] initWithKey:@"firstName"
                                ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:
                                ageSort,firstNameSort,  nil];
    fetchRequest.sortDescriptors = sortDescriptors;


注意: ascending:YES 是区分排序的



--------------3.20----------------

如果之前的工程里并没有引入coreData,我们则可以加入CoreData.FrameWork,然后command+N 



创建一个.xcdatamodel,并实现如下代码


@property (nonatomic, retain) NSManagedObjectModel *managedObjectModel;  
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;  
@property (nonatomic, retain) NSPersistentStoreCoordinator *persistentStoreCoordinator;




#pragma mark - 
#pragma mark - Core Data Stack

- (NSManagedObjectModel *)managedObjectModel
{
    if (nil != _managedObjectModel) {
        return _managedObjectModel;
    }
    
    _managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
    return _managedObjectModel;
}

- (NSManagedObjectContext *)managedObjectContext
{
    if (nil != _managedObjectContext) {
        return _managedObjectContext;
    }
    
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    
    if (self.persistentStoreCoordinator) {
        [_managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];
    }
    
    return _managedObjectContext;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (nil != _persistentStoreCoordinator) {
        return _persistentStoreCoordinator;
    }
    
    NSString *storeType = NSSQLiteStoreType;
    NSString *storeName = @"cdNBA.sqlite";
    
    NSError *error = NULL;
    NSURL *storeURL = [NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:storeName]];
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:storeType configuration:nilURL:storeURL options:nil error:&error]) {
        NSLog(@"Error : %@\n", [error localizedDescription]);
        NSAssert1(YES, @"Failed to create store %@ with NSSQLiteStoreType", [storeURL path]);
    }
    
    return _persistentStoreCoordinator;
}

#pragma mark -
#pragma mark Application's Documents Directory

- (NSString *)applicationDocumentsDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

我们每一次保存的时候都要调用一下managedObjectContextsave方法,因为context中创建的对象只是存在于内存中,所以我们要实际把他保存在sqlite里面,得到applicationDocumentsDirectory方法里的url, 前往->前往文件夹里可以看到你创建的sqlite


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值