ios 在已有项目添加CoreData

来源:互联网 发布:网络节点怎么设置 编辑:程序博客网 时间:2024/05/01 09:21

在创建项目初期,没有包含进CoreData。于是就在已建好的项目中加入CoreData。

  1.如果想在已建好的项目中加入CoreData,首先需要引入CoreData FrameWork。这里需要先点击target,然后再点击Build Phases,在下面的界面中找到LinkBinary With Libraries。点击箭头,展开这一项,然后再点击加号,出现Framework项界面。在搜索框中输入CoreData,这时出现CoreData.framework,选中它并点击Add按钮而加入CoreData FrameWork。这时会在target的下面出现CoreData.framework。为了文件的分类方便,可以把CoreData.framework拖入Frameworks中。然后保存就好了。然后在prefix.pch中加入#import。


2.加入数据模型,点击iWeather文件夹,然后点击右键,再点击New File。在弹出的界面的左边点击IOS,选择下面的CoreData,然后再点击右边的Data Model,之后点击Next,进入下一页,在这里弹出的界面需要在Save As中的.xcdatamodeld之前写入你的数据模型的名字。这里的名字任意写。我这里写的与项目名一样为iWeather。点击Create,在Show the Project Navigation将创建出一个数据模型iWeather.xcdatamodeld。



3.做好以上的这些工作之后,不要先急着去创建Entity。而是去Delegate中建立CoreData与Delegate的关联。这时,点击LWTAppDelegate.h,在@interface与@end之中加入以下代码;

@property (readonly,strong,nonatomic)NSManagedObjectContext *managedObjectContext;

@property (readonly,strong,nonatomic)NSManagedObjectModel *managedObjectModel;

@property (readonly,strong,nonatomic)NSPersistentStoreCoordinator *persistentStoreCoordinator;

 

- (void)saveContext;

- (NSURL *)applicationDocumentsDirectory;

上面的代码有几个名字术语:NSManagedObjectContext,NSManagedObjectModel,NSPersistentStoreCoordinator。 

(1).Managed Object Model管理数据模型:你可以将西看作是数据或者里包含了各个体的定信息一般来你会使用我们刚刚视觉编辑器来操作个物体添加属性建立属性之的关系等等当然你也可以使用代

(2). Persistent Store Coordinator持久性数据协调 你可以将西看作是数据库连你将置数据存的名字和位置以及数据存

(3). Managed Object Context 管理数据内容你可以将一部分看作是数据的实际内容也是整个数据而言最重要的部分这还基本上插入数据查询数据除数据的工作都在里完成

上面这段对术语的解释摘自:http://www.dasheyin.com/ios_jiao_cheng_core_data_shu_ju_chi_jiu_xing_cun_chu_ji_chu_jiao_cheng.html

4.之后打开LWTAppDelegate.m文件,在@implementation下面写入如下代码:

@synthesize managedObjectContext =_managedObjectContext;

@synthesize managedObjectModel = _managedObjectModel;

@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

然后在@end之前加入以下代码:

//相当于保存数据的方法

- (void)saveContext

{

    NSError *error = nil;

    NSManagedObjectContext *managedObjectContext =self.managedObjectContext;

    if (managedObjectContext !=nil) {

        if ([managedObjectContexthasChanges] && ![managedObjectContextsave:&error]) {

            NSLog(@"Unresolvederror %@, %@", error, [erroruserInfo]);

            abort();

        }

    }

}

 

#pragma mark - Core Data stack

 

// Returns the managed object context for the application.

// If the context doesn't already exist, it is created and bound to thepersistent store coordinator for the application.

- (NSManagedObjectContext *)managedObjectContext

{

    if (_managedObjectContext !=nil) {

        return _managedObjectContext;

    }

   

    NSPersistentStoreCoordinator *coordinator = [selfpersistentStoreCoordinator];

    if (coordinator != nil) {

        _managedObjectContext = [[NSManagedObjectContextalloc]init];

        [_managedObjectContextsetPersistentStoreCoordinator:coordinator];

    }

    return _managedObjectContext;

}

 

// Returns the managed object model for the application.

// If the model doesn't already exist, it is created from the application'smodel.

- (NSManagedObjectModel *)managedObjectModel

{

    if (_managedObjectModel !=nil) {

        return _managedObjectModel;

}

//这里一定要注意,这里的iWeather就是你刚才建立的数据模型的名字,一定要一致。否则会报错。

    NSURL *modelURL = [[NSBundlemainBundle]URLForResource:@"iWeather"withExtension:@"momd"];

    _managedObjectModel = [[NSManagedObjectModelalloc]initWithContentsOfURL:modelURL];

    return _managedObjectModel;

}

 

// Returns the persistent store coordinator for the application.

// If the coordinator doesn't already exist, it is created and theapplication's store added to it.

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator

{

    if (_persistentStoreCoordinator !=nil) {

        return _persistentStoreCoordinator;

    }

    //这里的iWeaher.sqlite,也应该与数据模型的名字保持一致。

    NSURL *storeURL = [[selfapplicationDocumentsDirectory]URLByAppendingPathComponent:@"iWeather.sqlite"];

   

    NSError *error = nil;

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinatoralloc]initWithManagedObjectModel:[selfmanagedObjectModel]];

    if (![_persistentStoreCoordinatoraddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:storeURLoptions:nilerror:&error]) {

        NSLog(@"Unresolvederror %@, %@", error, [erroruserInfo]);

        abort();

    }   

   

    return _persistentStoreCoordinator;

}

 

#pragma mark - Application's Documents directory

 

// Returns the URL to the application's Documents directory.

- (NSURL*)applicationDocumentsDirectory

{

    return[[[NSFileManagerdefaultManager]URLsForDirectory:NSDocumentDirectoryinDomains:NSUserDomainMask]lastObject];

}

到这里就做好了一切的准备工作了。然后去创建Entity吧。

5.打开iWeather.xcdatamodeld文件。通过Editor Style按钮调到视图模式下。如下图这样:


然后点击Add Entity按钮增加Entity。

这时咱们对Entity进行修改。点击Entity上,把那么修改为ArInfo。然后再点击AddAttribute按钮进行属性的添加。增加myid和myname这两个属性。属性类型都为String。

 


在做好这些之后,开始建立相应的.h和.m文件。右键点击iWeather文件夹,点击newFile,在弹出的窗口中选择NSManagedObject subclass,然后点击Next按钮将会出现选择实体窗口(这里不一定,也可能不出现,如果不出现,就要看生成的新文件是关联那个实体的,如果实体比较多,应该会出现,不出现就一个实体一个实体的建立),选择上之后再点击Next出现保存界面,保存既可以。在项目中将出现ArInfo.h和ArInfo.m这两个文件。


6.然后在LWTAViewController.h的@interface与@end中加入

@property (strong,nonatomic)NSManagedObjectContext *context;

在LWTAViewController.m中的@implementation之后加@synthesize context;

并在LWTAViewController.m添加

#import "ArInfo.h"

#import "LWTAppDelegate.h"

这两个头文件。然后在ViewDidLoad中加入如下代码:

LWTAppDelegate *delegate = (LWTAppDelegate *)[[UIApplication sharedApplication]delegate];//这里需要引进自己项目的委托,是让全局managedObjectContext起作用。

    self.context = delegate.managedObjectContext;

    ArInfo *arInfo = [NSEntityDescriptioninsertNewObjectForEntityForName:@"ArInfo"inManagedObjectContext:context];

    arInfo.myid=@"123";

    arInfo.myname=@"object-c";

    NSError *error = nil;

    if (![contextsave:&error]) {

        NSLog(@"%@",[errorlocalizedDescription]);

    }

   

    NSFetchRequest *fetchRequest = [[NSFetchRequestalloc]init];

    NSEntityDescription *entity = [NSEntityDescriptionentityForName:@"ArInfo"inManagedObjectContext:context];

    [fetchRequest setEntity:entity];

  

    NSArray *fetchObject = [contextexecuteFetchRequest:fetchRequesterror:&error];

    for (NSManagedObject *infoin fetchObject) {

        NSLog(@"id:%@",[infovalueForKey:@"myid"]);

        NSLog(@"name:%@",[infovalueForKey:@"myname"]);

}

这时运行程序。在All OutPut将输出:

2012-11-21 14:12:25.027 iWeather[2750:11603] id:123

2012-11-21 14:12:25.028 iWeather[2750:11603] name:object-c



总结:

1.添加CoreData框架
单击项目,选择Build Phases,继续选择Link Binary With Libraries,点假+号,搜索CoreData,Add就可以了。
2.修改perFix.pch文件
注意第11行

帮助
1
2
3
4
5
6
7
8
9
10
11
12
#import <Availability.h>
 
#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif
 
#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
    #import "NSObject+Subscripts.h"
    #import <CoreData/CoreData.h>
#endif

3.新建xcdatamodeld文件
添加文件。New File选择Core Data -》 Data Model  文件名称就是你的项目名
4.修改AppDelegate.h文件
增加以下代码

帮助
1
2
3
4
5
6
@property(nonatomic, retain, readonlyNSManagedObjectContext*managedObjectContext;
@property(nonatomic, retain, readonlyNSManagedObjectModel*managedObjectModel;
@property(nonatomic, retain, readonlyNSPersistentStoreCoordinator*persistentStoreCoordinator;
 
- (NSURL*)applicationDocumentsDirectory;
- (void)saveContext;

5.修改AppDelegate.m文件
增加以下代码

帮助
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
@synthesizemanagedObjectContext = _managedObjectContext;
@synthesizemanagedObjectModel = _managedObjectModel;
@synthesizepersistentStoreCoordinator = _persistentStoreCoordinator;
 
#pragma mark Core Data stack
/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext*)managedObjectContext
{
    if(_managedObjectContext != nil) {
        return_managedObjectContext;
    }
 
    NSPersistentStoreCoordinator*coordinator = [selfpersistentStoreCoordinator];
    if(coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContextalloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return_managedObjectContext;
}
 
/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created from the application's model.
 */
- (NSManagedObjectModel*)managedObjectModel
{
    if(_managedObjectModel != nil) {
        return_managedObjectModel;
    }
    NSURL*modelURL = [[NSBundlemainBundle] URLForResource:@"mima96_iphone"withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModelalloc] initWithContentsOfURL:modelURL];
    return_managedObjectModel;
}
 
/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator*)persistentStoreCoordinator
{
    if(_persistentStoreCoordinator != nil) {
        return_persistentStoreCoordinator;
    }
 
    NSURL*storeURL = [[selfapplicationDocumentsDirectory] URLByAppendingPathComponent:@"mima96_iphone.sqlite"];
 
    NSError*error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinatoralloc] initWithManagedObjectModel:[selfmanagedObjectModel]];
    if(![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:storeURL options:nilerror:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.
 
         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
 
         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.
 
         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
 
         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
 
         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
 
         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
 
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
 
    return_persistentStoreCoordinator;
}
 
#pragma mark Application's Documents directory
/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL*)applicationDocumentsDirectory
{
    return[[[NSFileManagerdefaultManager] URLsForDirectory:NSDocumentDirectoryinDomains:NSUserDomainMask] lastObject];
}
 
#pragma mark function
- (void)saveContext
{
    NSError*error = nil;
    NSManagedObjectContext*managedObjectContext = self.managedObjectContext;
    if(managedObjectContext != nil) {
        if([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

0 0