"应用程序包" Documents Library Caches Preferences tmp
NSString *path = [[NSBundle mainBundle] bundlePath]; NSLog(@"%@", path);Documents: 最常用的目录,iTunes同步该应用时会同步此文件夹中的内容,适合存储重要数据。
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; NSLog(@"%@", path);Library/Caches: iTunes不会同步此文件夹,适合存储体积大,不需要备份的非重要数据。
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject; NSLog(@"%@", path); Library/Preferences: iTunes同步该应用时会同步此文件夹中的内容,通常保存应用的设置信息。tmp: iTunes不会同步此文件夹,系统可能在应用没运行时就删除该目录下的文件,所以此目录适合保存应用中的一些临时文件,用完就删除。
NSString *path = NSTemporaryDirectory(); NSLog(@"%@", path);
1.获得文件路径
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; NSString *fileName = [path stringByAppendingPathComponent:@"123.plist"];2.存储
NSArray *array = @[@"123", @"456", @"789"]; [array writeToFile:fileName atomically:YES];3.读取
NSArray *result = [NSArray arrayWithContentsOfFile:fileName]; NSLog(@"%@", result);4.注意
1.使用方法
//1.获得NSUserDefaults文件 NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; //2.向文件中写入内容 [userDefaults setObject:@"AAA" forKey:@"a"]; [userDefaults setBool:YES forKey:@"sex"]; [userDefaults setInteger:21 forKey:@"age"]; //2.1立即同步 [userDefaults synchronize]; //3.读取文件 NSString *name = [userDefaults objectForKey:@"a"]; BOOL sex = [userDefaults boolForKey:@"sex"]; NSInteger age = [userDefaults integerForKey:@"age"]; NSLog(@"%@, %d, %ld", name, sex, age);2.注意
//1.遵循NSCoding协议 @interface Person : NSObject //2.设置属性 @property (strong, nonatomic) UIImage *avatar; @property (copy, nonatomic) NSString *name; @property (assign, nonatomic) NSInteger age; @end 实现协议方法 //解档 - (id)initWithCoder:(NSCoder *)aDecoder { if ([super init]) { self.avatar = [aDecoder decodeObjectForKey:@"avatar"]; self.name = [aDecoder decodeObjectForKey:@"name"]; self.age = [aDecoder decodeIntegerForKey:@"age"]; } return self; } //归档 - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.avatar forKey:@"avatar"]; [aCoder encodeObject:self.name forKey:@"name"]; [aCoder encodeInteger:self.age forKey:@"age"]; }
特别注意
如果需要归档的类是某个自定义类的子类时,就需要在归档和解档之前先实现父类的归档和解档方法。即 [super encodeWithCoder:aCoder] 和 [super initWithCoder:aDecoder] 方法;
2.使用
需要把对象归档是调用NSKeyedArchiver的工厂方法 archiveRootObject: toFile: 方法。
NSString *file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.data"]; Person *person = [[Person alloc] init]; person.avatar = self.avatarView.image; person.name = self.nameField.text; person.age = [self.ageField.text integerValue]; [NSKeyedArchiver archiveRootObject:person toFile:file];需要从文件中解档对象就调用NSKeyedUnarchiver的一个工厂方法 unarchiveObjectWithFile: 即可。
NSString *file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.data"]; Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:file]; if(person){ self.avatarView.image = person.avatar; self.nameField.text = person.name; self.ageField.text = [NSString stringWithFormat:@"%ld", person.age]; }3.注意
- (void)openDatabase { //1.设置文件名 NSString *filename = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.db"]; //2.打开数据库文件,如果没有会自动创建一个文件 NSInteger result = sqlite3_open(filename.UTF8String, &_sqlite3); if (result == SQLITE_OK) { NSLog(@"打开数据库成功!"); //3.创建一个数据库表 char *errmsg = NULL; sqlite3_exec(_sqlite3, "CREATE TABLE IF NOT EXISTS t_person(id integer primary key autoincrement, name text, age integer)", NULL, NULL, &errmsg); if (errmsg) { NSLog(@"错误:%s", errmsg); } else { NSLog(@"创表成功!"); } } else { NSLog(@"打开数据库失败!"); } }执行指令
- (void)insertData { NSString *nameStr; NSInteger age; for (NSInteger i = 0; i < 1000; i++) { nameStr = [NSString stringWithFormat:@"Bourne-%d", arc4random_uniform(10000)]; age = arc4random_uniform(80) + 20; NSString *sql = [NSString stringWithFormat:@"INSERT INTO t_person (name, age) VALUES('%@', '%ld')", nameStr, age]; char *errmsg = NULL; sqlite3_exec(_sqlite3, sql.UTF8String, NULL, NULL, &errmsg); if (errmsg) { NSLog(@"错误:%s", errmsg); } } NSLog(@"插入完毕!"); }查询指令
- (void)readData { NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:1000]; char *sql = "select name, age from t_person;"; sqlite3_stmt *stmt; NSInteger result = sqlite3_prepare_v2(_sqlite3, sql, -1, &stmt, NULL); if (result == SQLITE_OK) { while (sqlite3_step(stmt) == SQLITE_ROW) { char *name = (char *)sqlite3_column_text(stmt, 0); NSInteger age = sqlite3_column_int(stmt, 1); //创建对象 Person *person = [Person personWithName:[NSString stringWithUTF8String:name] Age:age]; [mArray addObject:person]; } self.dataList = mArray; } sqlite3_finalize(stmt); }4.总结
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.db"]; FMDatabase *database = [FMDatabase databaseWithPath:path]; if (![database open]) { NSLog(@"数据库打开失败!"); }值得注意的是,Path的值可以传入以下三种情况:
打开数据库:
[db open]
返回BOOL型。
关闭数据库:
[db close]
4.更新
在FMDB中,除查询以外的所有操作,都称为“更新”, 如:create、drop、insert、update、delete等操作,使用executeUpdate:方法(这个方法返回BOOL型)执行更新:
//常用方法有以下3种:
- (BOOL)executeUpdate:(NSString*)sql, ...
- (BOOL)executeUpdateWithFormat:(NSString*)format, ...
- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments
更新示例
创建数据库:
if ([db open]) { NSString *sqlCreateTable = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' INTEGER PRIMARY KEY AUTOINCREMENT, '%@' TEXT, '%@' INTEGER, '%@' TEXT)",TABLENAME,ID,NAME,AGE,ADDRESS]; BOOL res = [db executeUpdate:sqlCreateTable]; if (!res) { NSLog(@"error when creating db table"); }else{ NSLog(@"success to creating db table"); } [db close]; }添加数据:
if ([db open]) { NSString *insertSql1= [NSString stringWithFormat: @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')", TABLENAME, NAME, AGE, ADDRESS, @"张三", @"13", @"济南"]; BOOL res = [db executeUpdate:insertSql1]; NSString *insertSql2 = [NSString stringWithFormat: @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')", TABLENAME, NAME, AGE, ADDRESS, @"李四", @"12", @"济南"]; BOOL res2 = [db executeUpdate:insertSql2]; if (!res) { NSLog(@"error when insert db table"); } else { NSLog(@"success to insert db table"); } [db close]; }修改数据:
if ([db open]) { NSString *updateSql = [NSString stringWithFormat: @"UPDATE '%@' SET '%@' = '%@' WHERE '%@' = '%@'", TABLENAME, AGE, @"15" ,AGE, @"13"]; BOOL res = [db executeUpdate:updateSql]; if (!res) { NSLog(@"error when update db table"); }else{ NSLog(@"success to update db table"); } [db close]; }删除数据:
if ([db open]) { NSString *deleteSql = [NSString stringWithFormat:@"delete from %@ where %@ = '%@'",TABLENAME, NAME, @"张三"]; BOOL res = [db executeUpdate:deleteSql]; if (!res) { NSLog(@"error when delete db table"); } else { NSLog(@"success to delete db table"); } [db close]; }5.查询
if ([db open]) { //执行查询 NSString * sql = [NSString stringWithFormat: @"SELECT * FROM %@",TABLENAME]; FMResultSet * rs = [db executeQuery:sql]; //遍历结果集 while ([rs next]) { int Id = [rs intForColumn:ID]; NSString * name = [rs stringForColumn:NAME]; NSString * age = [rs stringForColumn:AGE]; NSString * address = [rs stringForColumn:ADDRESS]; NSLog(@"id = %d, name = %@, age = %@ address = %@", Id, name, age, address); } [db close]; }
6.线程安全
在多个线程中同时使用一个FMDatabase实例是不明智的。不要让多个线程分享同一个FMDatabase实例,它无法在多个线程中同时使用。 如果在多个线程中同时使用一个FMDatabase实例,会造成数据混乱等问题。所以,请使用 FMDatabaseQueue,它是线程安全的。以下是使用方法:
创建队列。 FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath]; 使用队列 [queue inDatabase:^(FMDatabase *database) { [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_1", [NSNumber numberWithInt:1]]; [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_2", [NSNumber numberWithInt:2]]; [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_3", [NSNumber numberWithInt:3]]; FMResultSet *result = [database executeQuery:@"select * from t_person"]; while([result next]) { } }];而且可以轻松地把简单任务包装到事务里:
[queue inTransaction:^(FMDatabase *database, BOOL *rollback) { [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_1", [NSNumber numberWithInt:1]]; [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_2", [NSNumber numberWithInt:2]]; [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_3", [NSNumber numberWithInt:3]]; FMResultSet *result = [database executeQuery:@"select * from t_person"]; while([result next]) { } //回滚 *rollback = YES; }];FMDatabaseQueue 后台会建立系列化的G-C-D队列,并执行你传给G-C-D队列的块。这意味着 你从多线程同时调用调用方法,GDC也会按它接收的块的顺序来执行。
如果应用中使用了多线程操作数据库,那么就需要使用FMDatabaseQueue来保证线程安全了。 应用中不可在多个线程中共同使用一个FMDatabase对象操作数据库,这样会引起数据库数据混乱。 为了多线程操作数据库安全,FMDB使用了FMDatabaseQueue,使用FMDatabaseQueue很简单,首先用一个数据库文件地址来初使化FMDatabaseQueue,然后就可以将一个闭包(block)传入inDatabase方法中。 在闭包中操作数据库,而不直接参与FMDatabase的管理。
示例代码:
FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:database_path]; dispatch_queue_t q1 = dispatch_queue_create("queue1", NULL); dispatch_queue_t q2 = dispatch_queue_create("queue2", NULL); dispatch_async(q1, ^{ for (int i = 0; i < 50; ++i) { [queue inDatabase:^(FMDatabase *db2){ NSString *insertSql1= [NSString stringWithFormat: @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)", TABLENAME, NAME, AGE, ADDRESS]; NSString * name = [NSString stringWithFormat:@"jack %d", i]; NSString * age = [NSString stringWithFormat:@"%d", 10+i]; BOOL res = [db2 executeUpdate:insertSql1, name, age,@"济南"]; if (!res) { NSLog(@"error to inster data: %@", name); } else { NSLog(@"succ to inster data: %@", name); } }]; } }); dispatch_async(q2, ^{ for (int i = 0; i < 50; ++i) { [queue inDatabase:^(FMDatabase *db2) { NSString *insertSql2= [NSString stringWithFormat: @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)", TABLENAME, NAME, AGE, ADDRESS]; NSString * name = [NSString stringWithFormat:@"lilei %d", i]; NSString * age = [NSString stringWithFormat:@"%d", 10+i]; BOOL res = [db2 executeUpdate:insertSql2, name, age,@"北京"]; if (!res) { NSLog(@"error to inster data: %@", name); } else { NSLog(@"succ to inster data: %@", name); } }]; } });
- (void)viewDidLoad { [super viewDidLoad]; /* * 关联的时候,如果本地没有数据库文件,Coreadata自己会创建 */ // 1. 上下文 NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; // 2. 上下文关连数据库 // 2.1 model模型文件 NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; // 2.2 持久化存储调度器 // 持久化,把数据保存到一个文件,而不是内存 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; // 2.3 设置CoreData数据库的名字和路径 NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"]; [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil]; context.persistentStoreCoordinator = store; _context = context; }CoreData的基本操作(CURD)
-(IBAction)addEmployee{ // 创建一个员工对象 //Employee *emp = [[Employee alloc] init]; 不能用此方法创建 Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context]; emp.name = @"wangwu"; emp.height = @1.80; emp.birthday = [NSDate date]; // 直接保存数据库 NSError *error = nil; [_context save:&error]; if (error) { NSLog(@"%@",error); } }读取数据 - Read
-(IBAction)readEmployee{ // 1.FetchRequest 获取请求对象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 2.设置过滤条件 // 查找zhangsan NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"zhangsan"]; request.predicate = pre; // 3.设置排序 // 身高的升序排序 NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO]; request.sortDescriptors = @[heigtSort]; // 4.执行请求 NSError *error = nil; NSArray *emps = [_context executeFetchRequest:request error:&error]; if (error) { NSLog(@"error"); } //NSLog(@"%@",emps); //遍历员工 for (Employee *emp in emps) { NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday); } }修改数据 - Update
-(IBAction)updateEmployee{ // 改变zhangsan的身高为2m // 1.查找到zhangsan // 1.1FectchRequest 抓取请求对象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 1.2设置过滤条件 // 查找zhangsan NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"zhangsan"]; request.predicate = pre; // 1.3执行请求 NSArray *emps = [_context executeFetchRequest:request error:nil]; // 2.更新身高 for (Employee *e in emps) { e.height = @2.0; } // 3.保存 NSError *error = nil; [_context save:&error]; if (error) { NSLog(@"%@",error); } }删除数据 - Delete
-(IBAction)deleteEmployee{ // 删除 lisi // 1.查找lisi // 1.1FectchRequest 抓取请求对象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 1.2设置过滤条件 // 查找zhangsan NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"lisi"]; request.predicate = pre; // 1.3执行请求 NSArray *emps = [_context executeFetchRequest:request error:nil]; // 2.删除 for (Employee *e in emps) { [_context deleteObject:e]; } // 3.保存 NSError *error = nil; [_context save:&error]; if (error) { NSLog(@"%@",error); } }二、CoreData的表关联
- (void)viewDidLoad { [super viewDidLoad]; /* * 关联的时候,如果本地没有数据库文件,Coreadata自己会创建 */ // 1. 上下文 NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; // 2. 上下文关连数据库 // 2.1 model模型文件 NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; // 2.2 持久化存储调度器 // 持久化,把数据保存到一个文件,而不是内存 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; // 2.3 设置CoreData数据库的名字和路径 NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"]; [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil]; context.persistentStoreCoordinator = store; _context = context; }基本操作
-(IBAction)addEmployee{ // 1. 创建两个部门 ios android //1.1 iOS部门 Department *iosDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context]; iosDepart.name = @"ios"; iosDepart.departNo = @"0001"; iosDepart.createDate = [NSDate date]; //1.2 Android部门 Department *andrDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context]; andrDepart.name = @"android"; andrDepart.departNo = @"0002"; andrDepart.createDate = [NSDate date]; //2. 创建两个员工对象 zhangsan属于ios部门 lisi属于android部门 //2.1 zhangsan Employee *zhangsan = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context]; zhangsan.name = @"zhangsan"; zhangsan.height = @(1.90); zhangsan.birthday = [NSDate date]; zhangsan.depart = iosDepart; //2.2 lisi Employee *lisi = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context]; lisi.name = @"lisi"; lisi.height = @2.0; lisi.birthday = [NSDate date]; lisi.depart = andrDepart; //3. 保存数据库 NSError *error = nil; [_context save:&error]; if (error) { NSLog(@"%@",error); } }读取信息 - Read
-(IBAction)readEmployee{ // 读取ios部门的员工 // 1.FectchRequest 抓取请求对象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 2.设置过滤条件 NSPredicate *pre = [NSPredicate predicateWithFormat:@"depart.name = %@",@"android"]; request.predicate = pre; // 4.执行请求 NSError *error = nil; NSArray *emps = [_context executeFetchRequest:request error:&error]; if (error) { NSLog(@"error"); } //遍历员工 for (Employee *emp in emps) { NSLog(@"名字 %@ 部门 %@",emp.name,emp.depart.name); } }其他功能与前几种类似,这里不在赘述
-(IBAction)readEmployee{ // 1.FectchRequest 抓取请求对象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 2.设置排序 // 按照身高的升序排序 NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO]; request.sortDescriptors = @[heigtSort]; // 3.模糊查询 // 3.1 名字以"wang"开头 //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"wangwu1"]; //request.predicate = pre; //名字以"1"结尾 //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",@"1"]; //request.predicate = pre; // 名字包含"wu1" //NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"wu1"]; //request.predicate = pre; // like 匹配 NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"*wu12"]; request.predicate = pre; // 4.执行请求 NSError *error = nil; NSArray *emps = [_context executeFetchRequest:request error:&error]; if (error) { NSLog(@"error"); } //遍历员工 for (Employee *emp in emps) { NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday); } }分页查询
-(void)pageSeacher{ // 1. FectchRequest 抓取请求对象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 2. 设置排序 // 身高的升序排序 NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO]; request.sortDescriptors = @[heigtSort]; // 3. 分页查询 // 总有共有15数据 // 每次获取6条数据 // 第一页 0,6 // 第二页 6,6 // 第三页 12,6 3条数据 // 3.1 分页的起始索引 request.fetchOffset = 12; // 3.2 分页的条数 request.fetchLimit = 6; // 4. 执行请求 NSError *error = nil; NSArray *emps = [_context executeFetchRequest:request error:&error]; if (error) { NSLog(@"error"); } // 5. 遍历员工 for (Employee *emp in emps) { NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday); } }
- (void)viewDidLoad { [super viewDidLoad]; // 一个数据库对应一个上下文 _companyContext = [self setupContextWithModelName:@"Company"]; _weiboContext = [self setupContextWithModelName:@"Weibo"]; }/**
-(NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName{ // 1. 上下文 NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; // 2. 上下文关连数据库 // 2.1 model模型文件 // 注意:如果使用下面的方法,如果 bundles为nil 会把bundles里面的所有模型文件的表放在一个数据库 //NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; // 改为以下的方法获取: NSURL *companyURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"]; NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:companyURL]; // 2.2 持久化存储调度器 // 持久化,把数据保存到一个文件,而不是内存 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; // 2.3 告诉Coredata数据库的名字和路径 NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *sqliteName = [NSString stringWithFormat:@"%@.sqlite",modelName]; NSString *sqlitePath = [doc stringByAppendingPathComponent:sqliteName]; [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil]; context.persistentStoreCoordinator = store; // 3. 返回上下文 return context; }添加元素
-(IBAction)addEmployee{ // 1. 添加员工 Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_companyContext]; emp.name = @"zhagsan"; emp.height = @2.3; emp.birthday = [NSDate date]; // 直接保存数据库 [_companyContext save:nil]; // 2. 发微博 Status *status =[NSEntityDescription insertNewObjectForEntityForName:@"Status" inManagedObjectContext:_weiboContext]; status.text = @"发了一条微博!"; status.createDate = [NSDate date]; [_weiboContext save:nil]; }