2016-09-21 56 views

回答

0

有時我需要爲應用程序準備數據。我創建另一個目標DataGenerator和AppDelegate中didFinishLaunch製作填充defaul境界對象:

NSString *fileName = @"Activities"; 


NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"json"]; 
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL]; 
NSError *error = nil; 
NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:[myJSON dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingOptions.MutableContainers error:&error]; 

NSMutableArray *sessionDays = [NSMutableArray array]; 
for (NSDictionary *dictionary in jsonDataArray) { 
    SessionDay *sessionDay = [[SessionDay alloc] initWithDictionary:dictionary]; 
    [sessionDays addObject:sessionDay]; 
} 

RLMRealm *realm = [RLMRealm defaultRealm]; 
[realm transactionWithBlock:^{ 
    [realm addObjects:sessionDays]; 
}]; 

打印此文件路徑在我的Mac

NSLog(@"Documents Directory: %@", [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]); 

將該文件拷貝到我的主要目標束。在主要目標AppDelegate中將該文件從軟件包複製到應用程序文件夾:

NSString *preLoadRealmPath = [[NSBundle mainBundle] pathForResource:@"default" ofType:@"realm"]; 

NSError *error; 
NSURL *url = [RLMRealmConfiguration defaultConfiguration].fileURL; 
[[NSFileManager defaultManager] copyItemAtPath:preLoadRealmPath toPath:url.path error:&error]; 
相關問題