1 ////////////////////////////////////////////////////////////////////////////
3 // Copyright 2015 Realm Inc.
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
9 // http://www.apache.org/licenses/LICENSE-2.0
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.
17 ////////////////////////////////////////////////////////////////////////////
19 #import "RLMAccessor.h"
20 #import "RLMOptionalBase.h"
21 #import "RLMObject_Private.h"
22 #import "RLMObjectStore.h"
23 #import "RLMProperty_Private.h"
26 #import <objc/runtime.h>
28 @interface RLMOptionalBase ()
29 @property (nonatomic) id unmanagedValue;
32 @implementation RLMOptionalBase
34 - (instancetype)init {
38 - (id)underlyingValue {
39 if ((_object && _object->_realm) || _object.isInvalidated) {
40 return RLMDynamicGet(_object, _property);
43 return _unmanagedValue;
47 - (void)setUnderlyingValue:(id)underlyingValue {
48 if ((_object && _object->_realm) || _object.isInvalidated) {
49 if (_property.isPrimary) {
50 @throw RLMException(@"Primary key can't be changed after an object is inserted.");
52 RLMDynamicSet(_object, _property, underlyingValue);
55 NSString *propertyName = _property.name;
56 [_object willChangeValueForKey:propertyName];
57 _unmanagedValue = underlyingValue;
58 [_object didChangeValueForKey:propertyName];
62 - (BOOL)isKindOfClass:(Class)aClass {
63 return [self.underlyingValue isKindOfClass:aClass] || RLMIsKindOfClass(object_getClass(self), aClass);
66 - (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
67 return [self.underlyingValue methodSignatureForSelector:sel];
70 - (void)forwardInvocation:(NSInvocation *)invocation {
71 [invocation invokeWithTarget:self.underlyingValue];
74 - (id)forwardingTargetForSelector:(__unused SEL)sel {
75 return self.underlyingValue;
78 - (BOOL)respondsToSelector:(SEL)aSelector {
79 if (id val = self.underlyingValue) {
80 return [val respondsToSelector:aSelector];
85 - (void)doesNotRecognizeSelector:(SEL)aSelector {
86 [self.underlyingValue doesNotRecognizeSelector:aSelector];