您的位置:首页 > 移动开发 > IOS开发

ios Core Data

2015-12-14 16:26 246 查看
在项目中创建后缀为” .xcdatamodel “的存储文件,在其attribute中创建属性,lineNum和lineText,类型为integer116和String

application中:

- (void)applicationWillResignActive:(NSNotification *)notification {
//获取appDelegate
BIDAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
//获取上下文context
NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSError *error;

for (int i = 1; i <= 4; i++) {
NSString *fieldName = [NSString stringWithFormat:@"line%d", i];
UITextField *theField = [self valueForKey:fieldName];
//创建提取请求
NSFetchRequest *request = [[NSFetchRequest alloc] init];
//创建托管对象(Managed Objects)
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:@"Line"
inManagedObjectContext:context];
//为请求设置Entity,指定希望的对象实体
[request setEntity:entityDescription];

//谓词(predicate)(断言?)类似于SQL中的where语言
//这句的意思是通知提取请求仅搜索lineNum 属性设置为i 的对象
NSPredicate *pred = [NSPredicate
predicateWithFormat:@"(lineNum = %d)", i];
//设置断言
[request setPredicate:pred];

NSManagedObject *theLine = nil;

//执行提取请求,执行之后,context将跟踪你对该数组(objects)中返回的托管对象(theLine)的任何修改,最终发送sava:时保存
NSArray *objects = [context executeFetchRequest:request
error:&error];

if (objects == nil) {
NSLog(@"There was an error!");
// Do whatever error handling is appropriate
}
if ([objects count] > 0)//原本存在,因为有设置断言,所以这里的count=1
theLine = [objects objectAtIndex:0];
else//初次存储
theLine = [NSEntityDescription
insertNewObjectForEntityForName:@"Line"
inManagedObjectContext:context];

[theLine setValue:[NSNumber numberWithInt:i] forKey:@"lineNum"];
[theLine setValue:theField.text forKey:@"lineText"];

}
//保存数据
[context save:&error];
}

viewDidLoad中

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
BIDAppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:@"Line"
inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];

NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
NSLog(@"There was an error!");
// Do whatever error handling is appropriate
}

for (NSManagedObject *oneObject in objects) {
NSNumber *lineNum = [oneObject valueForKey:@"lineNum"];
NSString *lineText = [oneObject valueForKey:@"lineText"];

NSString *fieldName = [NSString
stringWithFormat:@"line%d", [lineNum integerValue]];
UITextField *theField = [self valueForKey:fieldName];
theField.text = lineText;
}

UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification
object:app];
}

UITableView中:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[self.fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
id  sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = ;
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
// Configure the cell with data from the managed object.
return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
id  sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo name];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [self.fetchedResultsController sectionIndexTitles];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
return [self.fetchedResultsController sectionForSectionIndexTitle:title atIndex:index];
}

托管上下文:

// 指定存储数据文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES);
NSString *documentsDirectory = [paths lastObject];
NSString *persistentStorePath = [documentsDirectory stringByAppendingPathComponent:@"Model.sqlite"];
//创建托管对象模型
NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
//创建持久化存储协调器,并使用SQLite数据库做持久化存储
NSURL *storeUrl = [NSURL fileURLWithPath:persistentStorePath];
NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:managedObjectModel];
NSError *error = nil;
NSPersistentStore *persistentStore = [persistentStoreCoordinator
addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeUrl
options:nil
error:&error];

//创建托管对象上下文
NSManagedObjectContext *managedObjectContext = [[NSManagedObjectContext alloc]init];
[managedObjectContext setPersistentStoreCoordinator:persistentStoreCoordinator];

self.context = managedObjectContext;


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: