需实践操作

coredata 使用步骤(需实践操作) 1.创建数据模板文件(数据库)->(new->File->CoreData->DataModel)

2.添加实体(表)->(点开DataModel文件, 使用Add Ensty 添加实体, Attributes添加数据,添加关系RelationShips 比如班级跟学生是一对多的关系)

3.根据数据模板创建对象模型文件NSmanagedObject->(选中模型文件->editer->CreateNSManageObjectSub) 所有的实体类型都继承与NSManagedObject ,对个NSManagedObject对象对应着数据库中的一条记录 注意:需要在实体的右侧将Codegen 改为Manaual/None。否则会产生重定义的错误

4.生成上下文(NSManagedObjectContext)->

5.保存实体类对象到数据库(直接操作的是oc对象)

coredata 增删改查 数据同步实例 https://www.jianshu.com/p/5e8e8517a00c

coreData插入

 Employee *employee = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:self.context];  

 // 对实体对象的各个属性进行赋值

 [self.context  save:nil];

CoreData 查询使用NSFetchRequest//NSPredicate过滤条件

//1.1:FectchRequest 抓取请求对象  
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];  
    //1.2:设置过滤条件  
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@",@"张三"];  
    request.predicate = pre;  
    //1.3执行查询请求  
    NSArray *emps = [self.context executeFetchRequest:request error:nil];

coredata删除 -先查询在删除,最后保存

https://segmentfault.com/a/1190000004252566(图片)

数据库升级结果

新老数据全在同一个数据库文件中,无数据丢失,而且客户端会自动根据用户的版本选择数据模型。

数据库升级过程

1.修改psc的生成过程,即修改option参数,新的参数如下 //创建模型对象,传入nil会把bundle下所有模型文件管理起来 NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];

2.创建持久化存储助理:数据库 NSPersistentStoreCoordinator * store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; 3.请求自动轻量级迁移

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                             [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
                             nil];
   NSError *error = nil;

 //设置数据库相关信息 添加一个持久化存储库并设置存储类型和路径,NSSQLiteStoreType:SQLite作为存储库
  [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:sqlUrl options:options error:&error];

2.增加一个新版本的模型文件(Add Model Version)

3设置新的数据库模型版本(选中数据库模型)

4.修改新的数据模型版本,重新生成实体类

5.运行

coredata数据安全的解决办法(也就是coredata的多线程正确实现方式有哪些)

方法一: 2个context共用一个持久化存储助理psc,

context处理完成后通过通知的方式通知另一个context调用它自身的mergeChangesFromContextDidSaveNotification来自动同步数据。

 self.mainContext.persistentStoreCoordinator = self.persistentstoreCooedinator;

    self.backGroundContext1.persistentStoreCoordinator = self.persistentstoreCooedinator;

    self.backGroundContext.persistentStoreCoordinator = self.persistentstoreCooedinator;

    //添加NSManagerObjectContextDidChange监听,所有context的改变
[[NSNotificationCenter defaultCenter] addObserverForName:NSManagedObjectContextDidSaveNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification *note) {
        if (note.object == self.backGroundContext1) {
            dispatch_async(dispatch_get_main_queue(), ^{
               [self.mainContext performBlock:^{
                   [self.mainContext mergeChangesFromContextDidSaveNotification:note];
               }];
            });
        }
    }];

    //执行耗时的操作

    //执行完毕 调用自身的保存
    [self.backGroundContext1 performBlock:^{
        NSError * error = nil;
        if ([self.privateContext hasChanges]) {
             [self.privateContext save:&error];
        }
    }];

方法二:设置parentcontext,

一个parentcontext可以有多个childContext。因childContext没有实际的psc,所以save操作什么也不会做,会把操作push给parentContext,由parentContext 完成真正的save 操作,这样就实现了数据同步,这也是coreData的两层和三层结构的实现原理。

coredata 调试 1.打开Product,选择Edit Scheme.

2.选择Arguments,在下面的ArgumentsPassed On Launch中添加下面两个选项。(注意选项顺序不能错)

(1)-com.apple.CoreData.SQLDebug

(2)1

然后在运行程序过程中,如果操作了数据库,就会将SQL语句打印在输出面板。

ios8之后创建实体类的方式改变了

ios8之后生成NSManageObject subClass 的方式变为:

1.选中实体,

2.标题栏Edite ->Create NSManageObject subClass

注意:如果不将实体的Codegen进行修改,会产生重定义的错误。

**实体属性介绍: xcode 实体的右侧Attribute 栏各种属性值介绍

Type:属性格式 Optional: 默认选中,意思是属性是可选的。插入是省略 Transient: 属性值不存入数据库文件中,是瞬态的 defalut value 默认值 index in Spotlight 勾选表示为数据spotlight中生成索引,让coredata数据支持spolight中搜索

Validation 数据验证,保证存入数据合法

**关系名词解释 Relationships

Relationship:关系名

DEstination:目标对象

Inverse Relationship:反转关系,就是说关系是否是双向的

Delete Rules:实体间的删除规则

  no Action 选中标示关系中的原纪录仍然认为他与被删除的关系有着联系

Nullify 当destination被删除的时候。该选项将设置relationship中的destination为null。这是关系默认的删除规则,意思是如果删除了person,将设置address的person为nil

Cascade:当删除一条person记录时,也将删除与person相关的任意address记录,用于关系不是可选的情况

Deny用于one— to - many,如果我们有一个账号(Account)实体,跟一个用户(User)实体有着to-many relationship,并且删除规则设置为Deny。则一个账号记录仅仅当没有用户记录相关联的时候才能够删除,这确保了没有用户记录就没有账户记录。 1.数据库中: Z_PK是主键。系统自动创建。

xib 的outlet 用strong 还是weak https://www.cnblogs.com/zsw-1993/p/4879779.html

NSTimer Selector 循环引用 NSProxy解决NSTimer的内存泄漏 https://www.jianshu.com/p/5ac68c1b3d42 https://www.cnblogs.com/jukaiit/p/10599021.html

Typeof :元运算,放在运算数之前,返回一个字符串,说明运算数的类型。 跟__typeOf作用相同

查询引用计数值 NSLog(@"Retain count is %ld", CFGetRetainCount((__bridge CFTypeRef)self)); _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerSelector) userInfo:nil repeats:NO];

NSLog(@"Retain count is %ld", CFGetRetainCount((__bridge CFTypeRef)self));

[_timer invalidate];

NSLog(@"Retain count is %ld", CFGetRetainCount((__bridge CFTypeRef)self));


- (void) timerSelector {
NSLog(@"调用了NSTimer!");

}

如何检测内存泄漏

1.打开僵尸变量NSZombieEnabled,此时内存泄漏的对象会在控制台打印出“message sent to deallocated”的消息

2.product的分析工具analyze来分析

3.使用instrument的leak工具,有内存泄漏的地方会出现红色的小柱子

MRC autorelease

//MRC环境下: //第一步:生成并持有释放池NSAutoreleasePool对象; NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

// 在堆内存中生成一个对象 id obj = [[NSObject alloc] init];

// 第二步:调用autorelease方法,使对象加入连接池中; [obj autorelease];

//第三步:释放NSAutoreleasePool对象; [pool drain]; //向池中的所有对象调用release方法,此处由系统调用[obj release];

//obi已经释放,再次调用会崩溃 NSLog(@"%@", obj);

ARC

@autoreleasepool{// 这里生成NSAutoreleasePool对象 // 在堆内存中生成一个对象 id obj = [[NSObject alloc] init]; } // 在这里自动调用[pool drain];

NSString 引用计数 https://www.jianshu.com/p/ae4976ca92eb

深浅拷贝 https://blog.csdn.net/weixin_44544690/article/details/124843631 https://www.cnblogs.com/tlios/p/7645574.html

多线程 同步异步 并行穿行 https://www.pianshen.com/article/239654802/ https://cloud.tencent.com/developer/article/1337729

JSRUN前端笔记, 是针对前端工程师开放的一个笔记分享平台,是前端工程师记录重点、分享经验的一个笔记本。JSRUN前端采用的 MarkDown 语法 (极客专用语法), 这里属于IT工程师。