RLMThreadSafeReference.mm 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2016 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 "RLMThreadSafeReference_Private.hpp"
  19. #import "RLMUtil.hpp"
  20. @implementation RLMThreadSafeReference {
  21. realm::ThreadSafeReference _reference;
  22. id _metadata;
  23. Class _type;
  24. }
  25. - (instancetype)initWithThreadConfined:(id<RLMThreadConfined>)threadConfined {
  26. if (!(self = [super init])) {
  27. return nil;
  28. }
  29. REALM_ASSERT_DEBUG([threadConfined conformsToProtocol:@protocol(RLMThreadConfined)]);
  30. if (![threadConfined conformsToProtocol:@protocol(RLMThreadConfined_Private)]) {
  31. @throw RLMException(@"Illegal custom conformance to `RLMThreadConfined` by `%@`", threadConfined.class);
  32. } else if (threadConfined.invalidated) {
  33. @throw RLMException(@"Cannot construct reference to invalidated object");
  34. } else if (!threadConfined.realm) {
  35. @throw RLMException(@"Cannot construct reference to unmanaged object, "
  36. "which can be passed across threads directly");
  37. }
  38. RLMTranslateError([&] {
  39. _reference = [(id<RLMThreadConfined_Private>)threadConfined makeThreadSafeReference];
  40. _metadata = ((id<RLMThreadConfined_Private>)threadConfined).objectiveCMetadata;
  41. });
  42. _type = threadConfined.class;
  43. return self;
  44. }
  45. + (instancetype)referenceWithThreadConfined:(id<RLMThreadConfined>)threadConfined {
  46. return [[self alloc] initWithThreadConfined:threadConfined];
  47. }
  48. - (id<RLMThreadConfined>)resolveReferenceInRealm:(RLMRealm *)realm {
  49. if (!_reference) {
  50. @throw RLMException(@"Can only resolve a thread safe reference once.");
  51. }
  52. return RLMTranslateError([&] {
  53. return [_type objectWithThreadSafeReference:std::move(_reference) metadata:_metadata realm:realm];
  54. });
  55. }
  56. - (BOOL)isInvalidated {
  57. return !_reference;
  58. }
  59. @end