main.m 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2014 Realm Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. ////////////////////////////////////////////////////////////////////////////
  18. #import <Foundation/Foundation.h>
  19. #import <Realm/Realm.h>
  20. #import "Person.h"
  21. int main(int argc, const char * argv[])
  22. {
  23. @autoreleasepool {
  24. // Import JSON
  25. NSString *jsonFilePath = [[NSBundle mainBundle] pathForResource:@"persons" ofType:@"json"];
  26. NSData *jsonData = [NSData dataWithContentsOfFile:jsonFilePath];
  27. NSError *error = nil;
  28. NSArray *personDicts = [NSJSONSerialization JSONObjectWithData:jsonData
  29. options:0
  30. error:&error];
  31. if (error) {
  32. NSLog(@"There was an error reading the JSON file: %@", error.localizedDescription);
  33. return 1;
  34. }
  35. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  36. dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  37. dateFormatter.dateFormat = @"MMMM dd, yyyy";
  38. dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
  39. [[NSFileManager defaultManager] removeItemAtURL:[RLMRealmConfiguration defaultConfiguration].fileURL
  40. error:nil];
  41. RLMRealm *realm = [RLMRealm defaultRealm];
  42. [realm beginWriteTransaction];
  43. // Add Person objects in realm for every person dictionary in JSON array
  44. for (NSDictionary *personDict in personDicts) {
  45. Person *person = [[Person alloc] init];
  46. person.fullName = personDict[@"name"];
  47. person.birthdate = [dateFormatter dateFromString:personDict[@"birthdate"]];
  48. person.numberOfFriends = [(NSNumber *)personDict[@"friendCount"] integerValue];
  49. [realm addObject:person];
  50. }
  51. [realm commitWriteTransaction];
  52. // Print all persons from realm
  53. for (Person *person in [Person allObjects]) {
  54. NSLog(@"person persisted to realm: %@", person);
  55. }
  56. // Realm file saved at default path (~/Documents/default.realm)
  57. }
  58. return 0;
  59. }