今天闲来没事看了看CoreData,终于知道为什么大家更倾向于第三方库了,CoreData使用起来还是 挺麻烦的。
深层次的东西还没有深究,例如多线程、线程安全一类的,本次只是简单地了解了下CoreData的使用。
最重要的就是NSManagedObjectContext(上下文),我们对数据库的操作都是通过这个对象进行的。
1.首先需要加载实体模型文件,得到模型(编译后的后缀momd)
NSString*path = [[NSBundlemainBundle]pathForResource:@"CoreData"ofType:@"momd"];
NSManagedObjectModel*model = [[NSManagedObjectModelalloc]initWithContentsOfURL:[NSURLfileURLWithPath:path]];
2.建立数据库
NSString*homePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)lastObject];
NSString*dbPath = [homePathstringByAppendingString:@"/myCoreData.db"];
3.持久化存储协调器(连接数据库)
NSPersistentStoreCoordinator*coordinator = [[NSPersistentStoreCoordinatoralloc]initWithManagedObjectModel:model];
NSError*error =nil;
NSPersistentStore*store = [coordinatoraddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:[NSURLfileURLWithPath:dbPath]options:nilerror:&error];
4.创建上下文对象,操作数据库(设置上下文对象的协调器)
_context= [[NSManagedObjectContextalloc]initWithConcurrencyType:NSPrivateQueueConcurrencyType];
_context.persistentStoreCoordinator= coordinator;
下面一个小demo
#import"ViewController.h"
#import"Person.h"
@interfaceViewController()
@property(strong,nonatomic)IBOutletUITextField*nameField;
@property(strong,nonatomic)IBOutletUITextField*ageField;
@property(strong,nonatomic)IBOutletUITableView*tableView;
- (IBAction)addObject:(UIButton*)sender;
- (IBAction)delObject:(UIButton*)sender;
- (IBAction)updateObject:(UIButton*)sender;
- (IBAction)searchObject:(UIButton*)sender;
@end
staticNSString*identifier =@"cell";
@implementationViewController
{
NSManagedObjectContext*_context;
NSMutableArray*_dataArray;
NSInteger_selectedRow;
}
- (void)viewDidLoad
{
[superviewDidLoad];
[selfreadyCoreData];
[selfcreateUI];
}
- (void)readyCoreData
{
NSString*path = [[NSBundlemainBundle]pathForResource:@"CoreData"ofType:@"momd"];
NSManagedObjectModel*model = [[NSManagedObjectModelalloc]initWithContentsOfURL: [NSURLfileURLWithPath:path]];
NSString*homePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)lastObject];
NSString*dbPath = [homePathstringByAppendingString:@"/myCoreData.db"];
NSLog(@"%@",dbPath);
NSPersistentStoreCoordinator*coordinator = [[NSPersistentStoreCoordinatoralloc]initWithManagedObjectModel:model];
NSError*error =nil;
NSPersistentStore*store = [coordinatoraddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:[NSURLfileURLWithPath:dbPath]options:nilerror:&error];
if(store ==nil)
{
NSLog(@"%@",error.localizedDescription);
}
_context= [[NSManagedObjectContextalloc]initWithConcurrencyType:NSPrivateQueueConcurrencyType];
_context.persistentStoreCoordinator= coordinator;
Person*person1 = [NSEntityDescriptioninsertNewObjectForEntityForName:@"Person"inManagedObjectContext:_context];
person1.age= [NSNumbernumberWithInt:23];
person1.name=@"liming";
Person*person2 = [NSEntityDescriptioninsertNewObjectForEntityForName:@"Person"inManagedObjectContext:_context];
person2.name=@"wangqiang";
person2.age= [NSNumbernumberWithInt:30];
Person*person3 = [NSEntityDescriptioninsertNewObjectForEntityForName:@"Person"inManagedObjectContext:_context];
person3.name=@"lisi";
person3.age= [NSNumbernumberWithInt:18];
[_contextsave:&error];
NSFetchRequest*request = [[NSFetchRequestalloc]initWithEntityName:@"Person"];
NSArray*array = [_contextexecuteFetchRequest:requesterror:nil];
_dataArray= [arraymutableCopy];
}
- (void)createUI
{
[self.tableViewregisterClass:[UITableViewCellclass]forCellReuseIdentifier:identifier];
}
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
return_dataArray.count;
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
UITableViewCell*cell = [tableViewdequeueReusableCellWithIdentifier:identifier];
if(cell ==nil)
{
cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
Person*person = [_dataArrayobjectAtIndex:indexPath.row];
cell.textLabel.text= [NSStringstringWithFormat:@"姓名:%@年龄:%@",person.name,person.age];
returncell;
}
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
_selectedRow= indexPath.row;
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
}
- (IBAction)addObject:(UIButton*)sender {
if(self.nameField.text.length<=0||self.ageField.text.length<=0)
{
return;
}
Person*person = [NSEntityDescriptioninsertNewObjectForEntityForName:@"Person"inManagedObjectContext:_context];
person.name=self.nameField.text;
person.age= [NSNumbernumberWithInt:[self.ageField.textintValue]];
NSError*error =nil;
[_contextsave:&error];
[_dataArrayaddObject:person];
[self.tableViewreloadData];
}
- (IBAction)delObject:(UIButton*)sender
{
if(_selectedRow>=0&&_selectedRow<=_dataArray.count-1)
{
Person*person = [_dataArrayobjectAtIndex:_selectedRow];
[_contextdeleteObject:person];
BOOLret = [_contextsave:nil];
if(ret)
{
NSLog(@"删除成功");
[_dataArrayremoveObjectAtIndex:_selectedRow];
[self.tableViewreloadData];
}
else
{
NSLog(@"删除失败");
}
}
}
- (IBAction)updateObject:(UIButton*)sender {
NSFetchRequest*request = [[NSFetchRequestalloc]initWithEntityName:@"Person"];
NSPredicate*predicate = [[NSPredicatealloc]init];
predicate = [NSPredicatepredicateWithFormat:@"name='liming'"];
request.predicate= predicate;
NSArray*array = [_contextexecuteFetchRequest:requesterror:nil];
for(Person*personinarray)
{
person.name=@"lily";
person.age= [NSNumbernumberWithInt:15];
}
[_contextsave:nil];
NSFetchRequest*allRequest = [[NSFetchRequestalloc]initWithEntityName:@"Person"];
NSArray*allArray = [_contextexecuteFetchRequest:allRequesterror:nil];
_dataArray= [allArraymutableCopy];
[self.tableViewreloadData];
}
- (IBAction)searchObject:(UIButton*)sender {
NSFetchRequest*request = [[NSFetchRequestalloc]initWithEntityName:@"Person"];
NSPredicate*predicate = [[NSPredicatealloc]init];
NSString*txt_name =nil;
NSNumber*txt_age =nil;
if(self.nameField.text.length>0&&self.ageField.text.length>0)
{
txt_name =self.nameField.text;
txt_age = [NSNumbernumberWithInt:[self.ageField.textintValue]];
predicate = [NSPredicatepredicateWithFormat:@"name=%@ AND age=%@",txt_name,txt_age];
request.predicate= predicate;
NSArray*array = [_contextexecuteFetchRequest:requesterror:nil];
if(array.count==0)
{
NSLog(@"没有相关数据");
}
else
{
for(Person*personinarray)
{
NSLog(@"%@-%@",person.name,person.age);
}
}
}
elseif(self.nameField.text.length>0&&self.ageField.text.length==0)
{
txt_name =self.nameField.text;
predicate = [NSPredicatepredicateWithFormat:@"name=%@",txt_name];
request.predicate= predicate;
NSArray*array = [_contextexecuteFetchRequest:requesterror:nil];
if(array.count==0)
{
NSLog(@"没有相关数据");
}
else
{
for(Person*personinarray)
{
NSLog(@"%@-%@",person.name,person.age);
}
}
}
elseif(self.nameField.text.length==0&&self.ageField.text.length>0)
{
txt_age = [NSNumbernumberWithInt:[self.ageField.textintValue]];
predicate = [NSPredicatepredicateWithFormat:@"age=%@",txt_age];
request.predicate= predicate;
NSArray*array = [_contextexecuteFetchRequest:requesterror:nil];
if(array.count==0)
{
NSLog(@"没有相关数据");
}
else
{
for(Person*personinarray)
{
NSLog(@"%@-%@",person.name,person.age);
}
}
}
else
{
NSLog(@"请输入查询条件");
}
}
@end
实体对象Person类(需继承NSManagedObject)
#import
@interfacePerson :NSManagedObject
@property(nonatomic,strong)NSString*name;
@property(nonatomic,strong)NSNumber*age;
@end
#import"Person.h"
@implementationPerson
@synthesizeage;
@synthesizename;
@end