AppDelegate.m 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 "AppDelegate.h"
  19. #import <Realm/Realm.h>
  20. // Define your models
  21. @interface Dog : RLMObject
  22. @property NSString *name;
  23. @property NSInteger age;
  24. @property (readonly) RLMLinkingObjects *owners;
  25. @end
  26. RLM_ARRAY_TYPE(Dog)
  27. @interface Person : RLMObject
  28. @property NSString *name;
  29. @property RLMArray<Dog> *dogs;
  30. @end
  31. @implementation Person
  32. @end
  33. @implementation Dog
  34. + (NSDictionary *)linkingObjectsProperties
  35. {
  36. // Define "owners" as the inverse relationship to Person.dogs
  37. return @{ @"owners": [RLMPropertyDescriptor descriptorWithClass:Person.class propertyName:@"dogs"] };
  38. }
  39. @end
  40. @implementation AppDelegate
  41. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  42. {
  43. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
  44. self.window.rootViewController = [[UIViewController alloc] init];
  45. [self.window makeKeyAndVisible];
  46. [[NSFileManager defaultManager] removeItemAtURL:[RLMRealmConfiguration defaultConfiguration].fileURL error:nil];
  47. RLMRealm *realm = [RLMRealm defaultRealm];
  48. [realm transactionWithBlock:^{
  49. [Person createInRealm:realm withValue:@[@"John", @[@[@"Fido", @1]]]];
  50. [Person createInRealm:realm withValue:@[@"Mary", @[@[@"Rex", @2]]]];
  51. }];
  52. // Log all dogs and their owners using the "owners" inverse relationship
  53. RLMResults *allDogs = [Dog allObjects];
  54. for (Dog *dog in allDogs) {
  55. NSArray *ownerNames = [dog.owners valueForKeyPath:@"name"];
  56. NSLog(@"%@ has %lu owners (%@)", dog.name, (unsigned long)ownerNames.count, ownerNames);
  57. }
  58. return YES;
  59. }
  60. @end