如果數據是以關係方式構建的,則XML或JSON允許輕鬆保留該結構,然後輕鬆解析並保存在Core Data存儲中。您需要使用XML或JSON解析器,這會將您的數據轉換爲字典數組(如果您的數據結構需要它,可以將其數據轉換爲多個級別)。您只需循環訪問數組,然後深入挖掘詞典(如果合適的話,還有子數組和子詞典),並隨時添加對象到您的商店。
如果它是平面數據,一個簡單的單一表格將成爲核心數據中的單一實體,然後製表符分隔或CSV文本文件都可以(如果沒有任何內容,製表符分隔更容易解析數據本身內的標籤)。然後,您可以抓取單獨的行,將行分解爲數據位數組(這是製表符分隔使得超級簡單的地方),爲每行創建一個新對象,將其屬性設置爲數組元素,並保存上下文。
XML/JSON版本比這裏寫得更加複雜 - 搜索起來,你會發現很多例子 - 但這裏是製表符分隔的版本(假設你沒有一個巨大的球的數據不能合理地保存在內存中):
// Standard Core Data setup here, grabbing the managedObjectContext,
// which is what I'll call it
// Then parse your text
NSString *path = [[NSBundle mainBundle] pathForResource:@"YourTextFileName" ofType:@"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
NSArray *rows = [content componentsSeparatedByString:@"\n"];
// Now that we have rows we can start creating objects
YourManagedObject *yourManagedObject = nil;
for (NSString *row in rows) {
NSArray *elements = [row componentsSeparatedByString:@"\t"];
YourManagedObject *yourManagedObject = (YourManagedObject *)[NSEntityDescription insertNewObjectForEntityForName:@"YourManagedObject" inManagedObjectContext:managedObjectContext;
[YourManagedObject setName:[elements objectAtIndex:0]];
[YourManagedObject setCountry:[elements objectAtIndex:1]];
// Etc. You may need an NSNumberFormatter and/or an NSDateFormatter to turn
// your strings into dates and numbers, depending on your data types
[managedObjectContext save];
}
Poof,全部完成。
如果數據是靜態的,爲什麼不出貨的預填充的CoreData店的形式?你可以選擇你的風格,XML,SQLite等,然後不必擔心在設備上填充它。 – ImHuntingWabbits 2011-05-13 06:56:34
感謝您的建議。我可能會這樣做:-) – MrDatabase 2011-05-13 18:00:56