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

IOS CoreData的初始化使用

2014-03-24 11:45 344 查看

CoreData的使用

注:请注意红色选框步骤
创建工程时选择:
 


 
给coredata.modo文件添加数据
 


创建NSManageObject的子类
 


初始化一个rootTableViewController<基于tableviewcontroller>
 
.h文件中设置属性
#import <UIKit/UIKit.h>
@interface RootTableViewController : UITableViewController

//这里不需要添加readOnly
@property (strong, nonatomic) NSManagedObjectContext*managedObjectContext;
@property (retain, nonatomic) NSMutableArray*dataArray;

@end


 

- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions
方法中初始化RootViewController后面添加
root.manageContext = self.managedObjectContext;


调用其get方法来获取保证数据安全
 


 
在.m文件中对数据库的操作
// Copyright (c) 2014年袁仕崇. All rightsreserved.

#import "RootTableViewController.h"
#import "Entity.h"
#import "AppDelegate.h"
@interface RootTableViewController()

@end

@implementation RootTableViewController

-(void)dealloc
{
[_dataArray release];

[super dealloc];
}
-(id)initWithStyle:(UITableViewStyle)style
{
self =[super initWithStyle:style];
if (self) {
// Custominitialization
self.dataArray =[NSMutableArrayarray];
}
return self;
}

-(void)viewDidLoad
{
[super viewDidLoad];

//设置编辑和添加按钮
self.navigationItem.leftBarButtonItem= self.editButtonItem;
UIBarButtonItem*addButton= [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addButtonAction:)];
[self.navigationItem setRightBarButtonItem:addButton];

//读coredata 这里的Entity为.mode文件的名字
NSFetchRequest*fetchRequest= [[NSFetchRequest alloc] initWithEntityName:@"Entity"];
//创建谓词(用来查询)
NSDate *date= [NSDate date];
NSPredicate *predicate= [NSPredicate predicateWithFormat:@"time < %@", date];
//coredata查询
[fetchRequest setPredicate:predicate];
NSError *error= nil;
NSArray *array= [_managedObjectContext executeFetchRequest:fetchRequesterror:&error];
//将满足条件的数据传给_dataArray
[_dataArray setArray:array];

}
//重写编辑
-(void)setEditing:(BOOL)editinganimated:(BOOL)animated
{
[super setEditing:editing animated:animated];
[self.tableView setEditing:editing animated:editing];

}

-(void)addButtonAction:(UIButton*)button
{
//创建实体
Entity *time= [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:self.managedObjectContext];
//获取当前时间  实体.属性 = 值
time.time=[NSDate date];

[_dataArray insertObject:time atIndex:0];

NSIndexPath *indextPath= [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indextPath]withRowAnimation:UITableViewRowAnimationFade];
AppDelegate *appdelegate= (AppDelegate *)[[UIApplicationsharedApplication] delegate];
[appdelegate saveContext];

}
-(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
//Dispose of any resources that canbe recreated.
}

#pragma mark - Table view data source

-(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
return _dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"cell";
UITableViewCell*cell= [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell){
cell = [[[UITableViewCellalloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]autorelease];
}
Entity *time= (Entity *)[_dataArray objectAtIndex:indexPath.row];
cell.textLabel.text = [time.timedescription];
return cell;
}

-(void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyleforRowAtIndexPath:(NSIndexPath *)indexPath
{
//删除
if (editingStyle==UITableViewCellEditingStyleDelete) {
// Delete therow from the data source
//获取对应属性
Entity*time = (Entity *)[_dataArray objectAtIndex:indexPath.row];
//删除对应数据
[_managedObjectContextdeleteObject:time];
[_dataArrayremoveObject:time];

[tableView deleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationFade];
AppDelegate*appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
[appDelegate saveContext];
} else if (editingStyle == UITableViewCellEditingStyleInsert){
// Create a newinstance of the appropriate class, insertit into the array, and add a new rowto the table view
}
}

@end


 
 
在没有创建coreData的工程中使用coreData
一:



  
在预编译文件中引入coreData.h文件引入coreData.fremwork





在Appdelegate.h文件中添加方法
 


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

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


 
在Appdelegate.m文件中添加方法和属性



@synthesizemanagedObjectContext = _managedObjectContext;
@synthesizemanagedObjectModel = _managedObjectModel;
@synthesizepersistentStoreCoordinator = _persistentStoreCoordinator;


 
并且引入方法记得调用
 


- (void)saveContext
{
NSError *error= nil;
NSManagedObjectContext *managedObjectContext= self.managedObjectContext;
if (managedObjectContext!= nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code tohandle theerror appropriately.
// abort() causes the application togenerate a crash logand terminate. You should not use this function in ashipping application,although it may be useful during development.
NSLog(@"Unresolvederror %@, %@", error, [error userInfo]);
abort();
}
}
}

#pragma mark - Core Data stack

// Returns the managed objectcontext forthe application.
// If the context doesn't alreadyexist, itis created and bound to the persistent store coordinator for theapplication.
- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil) {
return _managedObjectContext;
}

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

// Returns the managed object modelfor theapplication.
// If the model doesn't alreadyexist, it iscreated from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL= [[NSBundle mainBundle] URLForResource:@"codeData" withExtension:@"momd"];
_managedObjectModel =[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}

// Returns the persistent storecoordinatorfor the application.
// If the coordinator doesn'talready exist,it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}

NSURL *storeURL= [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"codeData.sqlite"];

NSError *error= nil;
_persistentStoreCoordinator =[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@"Unresolvederror %@, %@", error, [error userInfo]);
abort();
}

return _persistentStoreCoordinator;
}

#pragma mark - Application'sDocumentsdirectory

// Returns the URL to theapplication'sDocuments directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}


 
coreData的添加
 


给所创建的数据添加新属性:
 


Ctrl+N创建ModeMapping



选择之前的(打对号)



点击Next选择新的
 



一定要选择现在的数据:(注意右边选框)
 


创建Subclass:
 


创建新的:
 




 点击NEXT后如果出现replace则选择替换掉 如果没有,生成新的Entity后删除原来的Entity
给其负值:


 
使用:
 


添加新的数据后一定要修改Appdelegate中的这个方法:
 


结束,如果有不正确之处,或者不懂之处,还往指正.一定回复.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 数据库 数据