zoukankan      html  css  js  c++  java
  • RestKit学习4:Database Seeding(生成数据库文件)

    本系列的前面几篇:

    RestKit学习1:引用RestKit项目
    RestKit学习2:使用RestKit发送和接受请求 
    RestKit学习3:CoreData 从模型到实体 

    RestKit中,生成数据库我们主要用 RKManagedObjectSeeder类。另外我们会利用项目的Target特征来生成数据库。

    下面是生成数据库的代码:

    //

    //  AppDelegate.m

    //  testRestKit02

    //

    //  Created by cybercare on 12-7-30.

    //  Copyright (c) 2012 cybercare. All rights reserved.

    //

     

    #import "AppDelegate.h"

    #import <RestKit/RestKit.h>

    #import <RestKit/CoreData.h>// If you are using Core Data…

     

    @implementation AppDelegate

     

     

    // This is typically configured as a secondary target on your project

    // Dump your seed data out of your backend system in JSON format

    // Add to the project as resources

    // Run the secondary target in the Simulator

    - (void)seedTheDatabase {

        // Setup the object manager

        RKObjectManager* objectManager = [RKObjectManagerobjectManagerWithBaseURLString:@"http://www.in4s.cn:8080/Inpads/json/"];

        

        // 需要存储的文件名

        objectManager.objectStore = [RKManagedObjectStoreobjectStoreWithStoreFilename:@"BAWSeed.sqlite"];

     

     

        // json 文件和 Core Data对象属性映射关系。

        RKManagedObjectMapping* mapping = [RKManagedObjectMappingmappingForEntityWithName:@"Series"inManagedObjectStore:objectManager.objectStore];

        

        mapping.primaryKeyAttribute = @"id";

        mapping.rootKeyPath = @"list";

        [mapping mapKeyPath:@"id"toAttribute:@"id"];

        [mapping mapKeyPath:@"name"toAttribute:@"name"];

        [mapping mapKeyPath:@"domestic"toAttribute:@"domestic"];

        [mapping mapKeyPath:@"logo_ext"toAttribute:@"logo_ext"];

        [mapping mapKeyPath:@"logo_hash"toAttribute:@"logo_hash"];

        [mapping mapKeyPath:@"seating"toAttribute:@"seating"];

        

        

        // Register our mappings with the provider

        [objectManager.mappingProvidersetObjectMapping:mapping forResourcePathPattern:@"/sync/series"];

        

        

        //

        // Load all the data from the file series.json into a seed database

        // The seeder will print instructions for how to copy the data to your app

        

        RKManagedObjectSeeder * seeder = [RKManagedObjectSeederobjectSeederWithObjectManager:objectManager];

        

        [seeder seedObjectsFromFile:@"series.json"withObjectMapping:mapping];

        [seeder finalizeSeedingAndExit];

        

        

    }

     

     

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

    {

        #ifdef RESTKIT_GENERATE_SEED_DB

            [self seedTheDatabase];

        #endif

     

        returnYES;

    }

     

     

    - (void)applicationWillResignActive:(UIApplication *)application

    {

     

        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

    }

     

    - (void)applicationDidEnterBackground:(UIApplication *)application

    {

        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 

        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    }

     

    - (void)applicationWillEnterForeground:(UIApplication *)application

    {

        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

    }

     

    - (void)applicationDidBecomeActive:(UIApplication *)application

    {

        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

    }

     

    - (void)applicationWillTerminate:(UIApplication *)application

    {

        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

    }

     

     

     

    @end

    我们这里的 series.json 文件的内容如下:

    {"error":0,"message":"成功","list":[{"id":1,"name":"传祺","domestic":"国产","logo_ext":"","logo_hash":"","seating":5},{"id":2,"name":"传祺GS5","domestic":"国产","logo_ext":"","logo_hash":"","seating":5}]}

    这里发现如果定义了 RESTKIT_GENERATE_SEED_DB 就执行生成数据库的代码。执行的整个逻辑代码均在 - (void)seedTheDatabase 函数中。

    我们可以简单的复制原先默认的 Targets,如下图,

    Snip20120802 2

    我们新建立的Targets中只需多增加一个宏定义:RESTKIT_GENERATE_SEED_DB

    在 Preprocessor Macros 中定义 RESTKIT_GENERATE_SEED_DB 如下:

    Snip20120802 3

    然后在运行时选择我们刚刚建立的 target 运行。

    Snip20120802 8

    就可以收到下面信息:

    2012-08-02 15:39:42.234 testRestKit02 copy[11454:c07] I restkit:RKLog.m:33 RestKit initialized...

    2012-08-02 15:39:43.445 testRestKit02 copy[11454:c07] I restkit.core_data:RKInMemoryManagedObjectCache.m:34 Creating thread-local entity cache for managed object context: <NSManagedObjectContext: 0x788d9d0>

    2012-08-02 15:39:43.447 testRestKit02 copy[11454:c07] I restkit.core_data:RKManagedObjectSeeder.m:159 Seeded 0 objects from series.json...

    2012-08-02 15:39:43.453 testRestKit02 copy[11454:c07] I restkit.core_data:RKManagedObjectSeeder.m:178 A seeded database has been generated at '/Users/cybercare/Library/Application Support/iPhone Simulator/5.1/Applications/A06C7739-5B26-4DF7-B62F-917EAFD23A8D/Documents/BAWSeed.sqlite'. Please execute `open "/Users/cybercare/Library/Application Support/iPhone Simulator/5.1/Applications/A06C7739-5B26-4DF7-B62F-917EAFD23A8D/Documents"` in your Terminal and copy BAWSeed.sqlite to your app. Be sure to add the seed database to your "Copy Resources" build phase.


    这里我们可以看到一个空白数据库被成功建立了。

    在上面提醒的/Users/cybercare/Library/Application Support/iPhone Simulator/5.1/Applications/A06C7739-5B26-4DF7-B62F-917EAFD23A8D/Documents/ 目录下可以看到我们需要的 sqlite 数据库文件。

    用 FireFox 的插件 SQLite Manager 我们可以清晰的看到这个表的结构。

    Snip20120802 9

    参考资料:

    Presentation: Introduction to RestKit
    https://github.com/RestKit/RestKit/
    http://www.readncode.com/blog/Seeding-CoreData-with-RestKit/ 
    http://restkit.org/api/master/Classes/RKManagedObjectSeeder.html

  • 相关阅读:
    hdu-2814-Interesting Fibonacci-斐波那契周期节
    servletContext
    Java中的NIO和IO的对比分析
    sessionID和cookie
    会话跟踪session cookie
    C++中的头文件和源文件
    C++ 头文件
    二叉线索树
    C 二叉树 1
    C 二叉树
  • 原文地址:https://www.cnblogs.com/ghj1976/p/2620145.html
Copyright © 2011-2022 走看看