質問

ってリストの作成アプリのバックでの核データです。

いいデフォルトリスト10に空港の項目では、ユーザーとなります。

はありません。

のお役に立てるようよろしくお願いいたします。よろしくお願いします。

役に立ちましたか?

解決

ここでは最良の方法だ(とSQLの知識は必要ありません):
あなたのリストのアプリと同じオブジェクトモデルを使用してクイックコアデータのiPhoneアプリ(あるいはMacのアプリ)を作成します。あなたが保存したいデフォルトの管理対象オブジェクトを保存するための数行のコードを書きます。次に、シミュレータでそのアプリケーションを実行します。今、〜/ライブラリ/ Application Support / iPhoneシミュレータ/ユーザ/アプリケーションにアクセスしてください。 GUIDの間でアプリケーションを検索し、その後、ちょうどあなたのリストのアプリのプロジェクトフォルダにsqliteのストアをコピーします。

彼らはCoreDataBooks例で行うように続いて、その店をロードします。

他のヒント

はいCoreDataBooks例は、実際にそこにあるこれを行い、あなたはここで、コードダウンロードすることができます:<のhref =「http://developer.apple.com/iphone/library/samplecode/CoreDataBooks/」のrel =「noreferrerを」 >サンプルコードする

あなたがやっていることは(ちょうどあなたのようなお店を初期化するために、通常の手順を使用して、内部ストア(データベース)は、他の店で、その後、あなたは、単にあなたのコードを実行し、CoreDataBooks例で説明したように、コードを実行させます作成することですコードは)以下のスニペット。ストアが初期化されていたら、NSManagedObjectContextを作成し、作成した永続ストアでそれを初期化し、あなたが必要とするすべてのエンティティを挿入して、コンテキストを保存したいと思うでしょう。

検索.sqliteで~/Library/Developerタイプをおよび/開発者の下で見て、日付でソートすることはあなたの最も最近の.sqliteを与える:コンテキストが正常に保存されたら、

は、Finderやフォルダに移動して行き、その後、アプリケーションを停止することができますコードが実行された時刻と一致する必要がありますデータベースは、あなたがこの店を取り、あなたのプロジェクトのリソースとして追加することができます。このファイルは、永続ストアコーディネータで読み取ることができます。

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

if (persistentStoreCoordinator) {
    return persistentStoreCoordinator;
}


NSString *storePath = [[self applicationDocumentsDirectory]      stringByAppendingPathComponent: @"CoreDataBooks.sqlite"];
 /*
  Set up the store.
 For the sake of illustration, provide a pre-populated default store.
 */
NSFileManager *fileManager = [NSFileManager defaultManager];
// If the expected store doesn't exist, copy the default store.
if (![fileManager fileExistsAtPath:storePath]) {
  NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"CoreDataBooks"      ofType:@"sqlite"];
 if (defaultStorePath) {
 [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
 }
}

NSURL *storeUrl = [NSURL fileURLWithPath:storePath];

 NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber   numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; 
  persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];

 NSError *error;
 if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {
  // Update to handle the error appropriately.
  NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
 exit(-1);  // Fail
}    

return persistentStoreCoordinator;
}

希望に役立ちます。

-Oscar

この方法を使えば、別のアプリを作るか、または任意のSQLの知識を持っている必要はありません。あなただけのあなたの最初のデータのためのJSONファイルを作成できるようにする必要があります。

私はコアデータにそれらを挿入し、オブジェクトに解析JSONファイルを使用します。アプリの初期化時に、私はこれを行います。また、私は次の時間は、スクリプトは、それが最初のデータが既に初期化されていることを見て走るので、私はこのエンティティを設定された初期データを挿入した後、この初期データは既に、挿入されているかどうかを示す私のコアデータ内の1つのエンティティを作成します。

オブジェクトにJSONファイルを読み込むには:

NSString *initialDataFile = [[NSBundle mainBundle] pathForResource:@"InitialData" ofType:@"json"];
NSError *readJsonError = nil;
NSArray *initialData = [NSJSONSerialization
                        JSONObjectWithData:[NSData dataWithContentsOfFile:initialDataFile]
                        options:kNilOptions
                        error:&readJsonError];

if(!initialData) {
    NSLog(@"Could not read JSON file: %@", readJsonError);
    abort();
}

次に、あなたがこのようなことのためにエンティティオブジェクトを作ることができます:

[initialData enumerateObjectsUsingBlock:^(id objData, NSUInteger idx, BOOL *stop) {

    MyEntityObject *obj = [NSEntityDescription
                          insertNewObjectForEntityForName:@"MyEntity"
                          inManagedObjectContext:dataController.managedObjectContext];

    obj.name = [objData objectForKey:@"name"];
    obj.description = [objData objectForKey:@"description"];

    // then insert 'obj' into Core Data

}];

あなたがこれを行う方法の詳細な説明をしたい場合は、このチュートリアルをチェックアウト: http://www.raywenderlich.com/12170/core-データ・チュートリアル - どのようツーpreloadimport-既存のデータ更新する

10の項目について、あなただけのアプリデリゲートにapplicationDidFinishLaunching:以内にこれを行うことができます。

、メソッドを定義し、あなたの空港の項目を管理する担当エンティティのインスタンスを作成し、移入insertPredefinedObjectsを言うと、あなたのコンテキストを保存します。あなたは、ファイルの属性を読み取るか、単にあなたのコードでそれらをハードコーディングするのどちらか。その後、applicationDidFinishLaunching:内でこのメソッドを呼び出します。

受けていることを忘れてはな場合にCoreDataBooksのコード例は、これらのiOSデータ保存ガイドライン

https://developer.apple.com/icloud/documentation/data-storage/

またアプリの拒否のためのコピー(読み取り専用)pre-人口データベースの文書をディレクトリになるという新たな目標に向けて"そして、バックアップiCloud、Appleていただくことを実現させるにはユーザー生成ファイルです。

のガイドライン上で提供ソフトウェア技術者が中心で抜:

  • 店舗のDBのキャッシュディレクトリに、優雅に取扱う場合は、OS purgesのキャッシュ-で再構築のDB,そのルールで。

  • 定的なキャッシュ属性のDBのファイルは、少し難解できるという異なるOSのバージョン.

とは思わないでもトリッキーがないサービスめることができるコード例は、仕事とiCloud...

だから私は(おそらくJSONから)辞書からロードし、データベースを移入する一般的な方法を開発しました。 それONLY(安全なチャネルからの)信頼できるデータに使用する必要があり、それは循環参照とスキーマの移行を扱うことができない問題がある可能性が...しかし、私のような単純なユースケースのために、それは問題ないはずです。

ここではそれが行く

- (void)populateDBWithDict:(NSDictionary*)dict
               withContext:(NSManagedObjectContext*)context
{
    for (NSString* entitieName in dict) {

        for (NSDictionary* objDict in dict[entitieName]) {

            NSManagedObject* obj = [NSEntityDescription insertNewObjectForEntityForName:entitieName inManagedObjectContext:context];
            for (NSString* fieldName in objDict) {

                NSString* attName, *relatedClass, *relatedClassKey;

                if ([fieldName rangeOfString:@">"].location == NSNotFound) {
                    //Normal attribute
                    attName = fieldName; relatedClass=nil; relatedClassKey=nil;
                } else {
                    NSArray* strComponents = [fieldName componentsSeparatedByString:@">"];
                    attName = (NSString*)strComponents[0];
                    relatedClass = (NSString*)strComponents[1];
                    relatedClassKey = (NSString*)strComponents[2];
                }
                SEL selector = NSSelectorFromString([NSString stringWithFormat:@"set%@:", attName ]);
                NSMethodSignature* signature = [obj methodSignatureForSelector:selector];
                NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature];
                [invocation setTarget:obj];
                [invocation setSelector:selector];

                //Lets set the argument
                if (relatedClass) {
                    //It is a relationship
                    //Fetch the object
                    NSFetchRequest* query = [NSFetchRequest fetchRequestWithEntityName:relatedClass];
                    query.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:relatedClassKey ascending:YES]];
                    query.predicate = [NSPredicate predicateWithFormat:@"%K = %@", relatedClassKey, objDict[fieldName]];

                    NSError* error = nil;
                    NSArray* matches = [context executeFetchRequest:query error:&error];


                    if ([matches count] == 1) {
                        NSManagedObject* relatedObject = [matches lastObject];
                        [invocation setArgument:&relatedObject atIndex:2];
                    } else {
                        NSLog(@"Error! %@ = %@ (count: %d)", relatedClassKey,objDict[fieldName],[matches count]);
                    }


                } else if ([objDict[fieldName] isKindOfClass:[NSString class]]) {

                    //It is NSString
                    NSString* argument = objDict[fieldName];
                    [invocation setArgument:&argument atIndex:2];
                } else if ([objDict[fieldName] isKindOfClass:[NSNumber class]]) {

                    //It is NSNumber, get the type
                    NSNumber* argument = objDict[fieldName];
                    [invocation setArgument:&argument atIndex:2];

                }
                [invocation invoke];


            }

            NSError *error;
            if (![context save:&error]) {
                NSLog(@"%@",[error description]);
            }
        }
    }   
}

とJSONからロード...

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"initialDB" ofType:@"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:filePath];

NSError* error;
NSDictionary *initialDBDict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                           options:NSJSONReadingMutableContainers error:&error];

[ self populateDBWithDict:initialDBDict withContext: [self managedObjectContext]];

JSON例

    {
    "EntitieA": [ {"Att1": 1 }, {"Att1": 2} ],
    "EntitieB": [ {"Easy":"AS ABC", "Aref>EntitieA>Att1": 1} ]
    }

{
    "Country": [{"Code": 55, "Name": "Brasil","Acronym": "BR"}],
    "Region": [{"Country>Country>code": 55, "Code": 11, "Name": "Sao Paulo"},
               {"Country>Country>code": 55, "Code": 31, "Name": "Belo Horizonte"}]
}

どのようにチェックについてのオブジェクトが存在する場合としない場合は、いくつかのデータを持つものを作成する?

NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Settings"];
_managedObjectSettings = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

if ([_managedObjectSettings count] == 0) {
    // first time, create some defaults
    NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Settings" inManagedObjectContext:managedObjectContext];

    [newDevice setValue:[NSNumber numberWithBool: YES ] forKey:@"speed"];
    [newDevice setValue:[NSNumber numberWithBool: YES ] forKey:@"sound"];
    [newDevice setValue:[NSNumber numberWithBool: NO ] forKey:@"aspect"];
    [newDevice setValue:[NSNumber numberWithBool: NO  ] forKey: @"useH264"];
    [newDevice setValue:[NSNumber numberWithBool: NO ] forKey: @"useThumbnail"];

    NSError *error = nil;
    // Save the object to persistent store
    if (![managedObjectContext save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }
}

この答えの方のみご提出ください

  • を含む前の人口データベースのアプリ
  • 作成アプリのためのマルチプラットフォーム(iOS、Androidなど)

またprepopulated SQLiteデータベースデザインしました。その時に作っていただけるようiOSバージョンのアプリで使用核データです。なので私はかなり長時間の学習コミュニケーションを書き換えコードをprepopulateのデータベースです。学習にどのようなプロセス両プラットフォームに必要な多くの研究、試作、エラーになります。がありましたもしくは重複していた以上にいえる。

最終的に私たはSQLiteデータベースからの私のAndroidプロジェクト.そのFMDBするラッパーには直接アクセス、データベースです。の特典:

  • みは必要になりprepopulatedデータベース。
  • を必要としませんパラダイムシフトができます。の構文とAndroid FMDBが異なり、まだかなり似ています。
  • くりはらう質問を行います。
  • できる全文検索します。

がん遺憾の学習コアのデータを組み合わせたいと思って保存され多くの時間だけでこだわりSQLite.

だからiOSおよびその計画はAndroid思用SQLiteラッパーのようなFMDBまたはその他のソフトウェアprepopulateのデータベースです。ですが技術的に抽出SQLiteデータベースとすprepopulateとのコミュニケーションは、スキーマ(テーブルやカラム名など) する奇妙な名前が命名されます。

ちなみに、ない場合を修正する必要があprepopulatedデータベースがしたいコピーする文書のディレクトリの後にアプリをインストール。でアクセスから直接のコストもまあまあでした。

// get url reference to databaseName.sqlite in the bundle
let databaseURL: NSURL = NSBundle.mainBundle().URLForResource("databaseName", withExtension: "sqlite")!

// convert the url to a path so that FMDB can use it
let database = FMDatabase(path: databaseURL.path)

このような二枚。

更新

私は現在利用中の SQLite.迅速かつ よFMDBで統合に迅速す。

デフォルトを格納するための別の方法は、NSUserDefaultsの方法によって発見されました。 (驚き!) そして、その簡単ます。

いくつかによって推奨、applicationDidFinishLaunchingにそれを置く。

10デフォルトの所定の場合において、Airport0スルー9

設定

NSUserDefaults *nud = [NSUserDefaults standardUserDefaults];
[nud setString:@"MACADDRESSORWHY" forKey:@"Airport0"];
    ...
[nud setString:@"MACADDRESSORWHY" forKey:@"Airport9"];
[nud synchronize];

または

[[NSUserDefaults standardUserDefaults] setString:@"MACADDRESSORWHY" forKey:@"Airport9"]];
     ...
[[NSUserDefaults standardUserDefaults] synchronize];

そして、デフォルト値を取得します。

NSString *air0 = [[NSUserDefaults standardUserDefaults] stringForKey:@"Airport0"];

これは私のために働きました。これは、<のhref = "https://stackoverflow.com/users/6654061/andreaでに答えるhref="https://stackoverflow.com/a/47953340/8253993">このアンドレア東ソーおよびこのブログに触発さ。答えを持つ唯一の問題は、FileManagerのでsqliteのファイルを移動する際に、データ損失の可能性があるということです。私が代わりにFileManager.default.copyItemのreplacePersistentStoreを使用して、データの約500行を保存

ステップ1
他のアプリで、あなたのコアデータを移入し、このコードを使用してファイルのパスを取得します:

let paths = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
print(documentsDirectory)

ステップ2
.sqlite拡張子を使用して3つのファイルには、Xcodeプロジェクトにドラッグします。 (ターゲットオプションに追加]を選択してください)。

ステップ3
AppDelegate.swiftでのアプリの最初の実行を確認するための関数を作成します。

func isFirstLaunch() -> Bool {
    let hasBeenLaunchedBeforeFlag = "hasBeenLaunchedBeforeFlag"
    let isFirstLaunch = !UserDefaults.standard.bool(forKey: hasBeenLaunchedBeforeFlag)
    if (isFirstLaunch) {
        UserDefaults.standard.set(true, forKey: hasBeenLaunchedBeforeFlag)
        UserDefaults.standard.synchronize()
    }
    return isFirstLaunch
}

ステップ4
SQLiteデータベースを移動する必要がある場所のURLを取得するにはAppDelegate.swiftでこの機能をコピーします:

func getDocumentsDirectory()-> URL {
    let paths = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

ステップ5
この1とpersistentContainerの宣言を置き換えます:

// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "ProjectName")

    let storeUrl = self.getDocumentsDirectory().appendingPathComponent("FileName.sqlite")

    if UserDefaults.isFirstLaunch() {
        let seededDataUrl = Bundle.main.url(forResource: "FileName", withExtension: "sqlite")
        try! container.persistentStoreCoordinator.replacePersistentStore(at: storeUrl, destinationOptions: nil, withPersistentStoreFrom: seededDataUrl!, sourceOptions: nil, ofType: NSSQLiteStoreType)
    }

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top