1 // Copyright 2017 Google
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 #import "Private/FIRAppAssociationRegistration.h"
17 #import <objc/runtime.h>
19 @implementation FIRAppAssociationRegistration
21 + (nullable id)registeredObjectWithHost:(id)host
23 creationBlock:(id _Nullable (^)(void))creationBlock {
25 SEL dictKey = @selector(registeredObjectWithHost:key:creationBlock:);
26 NSMutableDictionary<NSString *, id> *objectsByKey = objc_getAssociatedObject(host, dictKey);
28 objectsByKey = [[NSMutableDictionary alloc] init];
29 objc_setAssociatedObject(host, dictKey, objectsByKey, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
31 id obj = objectsByKey[key];
32 NSValue *creationBlockBeingCalled = [NSValue valueWithPointer:dictKey];
34 if ([creationBlockBeingCalled isEqual:obj]) {
35 [NSException raise:@"Reentering registeredObjectWithHost:key:creationBlock: not allowed"
36 format:@"host: %@ key: %@", host, key];
40 objectsByKey[key] = creationBlockBeingCalled;
41 obj = creationBlock();
42 objectsByKey[key] = obj;