iRSSの日記

はてなダイアリーiRSSの日記の続き

Core Dataのデフォルトデータを用意するには?

How do I initialize a store with default data?

There are two issues here: creating the data, and ensuring the data is imported only once.

There are several ways to create the data.

You can create the managed objects directly in code (as trivially illustrated in NSPersistentDocument Core Data Tutorial).
You can create a property list?or some other file-based representation?of the data, and store it as an application resource. When you want to use it, you must open the file and parse the representation to create managed objects.
You can create a separate persistent store that contains the default data. When you want to use it, you must copy the objects from the defaults store to the newly-created store.
There are also several ways to ensure that the defaults are imported only once. If you are creating a document-based application using , you can follow the guideline described in NSPersistentDocument Core Data Tutorial (that is, you initialize the defaults in initWithType:error:).

If you are using a non-document-based application and started with the standard application template then after these lines of code:

if ( ![fileManager fileExistsAtPath:applicationSupportFolder isDirectory:NULL] )
{
????[fileManager createDirectoryAtPath:applicationSupportFolder attributes:nil];
}
url = [NSURL fileURLWithPath: [applicationSupportFolder stringByAppendingPathComponent: @"Delete.xml"]];
you can add a check to determine whether the file at the url exists. If it doesn't, you need to import the data.

If there is some reason that there might be a possibility that the store (hence file) gets created but the data is not imported, then you might consider adding a metadata flag to the store. You can check the metadata (using metadataForPersistentStoreWithURL:error:) more efficiently than executing a fetch (and it does not require you to hard code any default data values).