summaryrefslogtreecommitdiff
path: root/swift/src/IceObjc/LocalObject.mm
blob: 092397a308a9036b24468635e83a0c8027b632ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// Copyright (c) ZeroC, Inc. All rights reserved.
//

#include <unordered_map>

#import "LocalObject.h"

namespace
{
    std::unordered_map<void*, __weak ICELocalObject*> cachedObjects;
}

@implementation ICELocalObject

-(instancetype) initWithCppObject:(std::shared_ptr<void>)cppObject
{
    assert(cppObject);
    self = [super init];
    if(!self)
    {
        return nil;
    }

    _cppObject = std::move(cppObject);

    @synchronized([ICELocalObject class])
    {
        assert(cachedObjects.find(_cppObject.get()) == cachedObjects.end());
        cachedObjects.insert(std::make_pair(_cppObject.get(), self));
    }
    return self;
}

+(nullable instancetype) getHandle:(std::shared_ptr<void>)cppObject
{
    if(cppObject == nullptr)
    {
        return nil;
    }
    @synchronized([ICELocalObject class])
    {
        std::unordered_map<void*, __weak ICELocalObject*>::const_iterator p = cachedObjects.find(cppObject.get());
        if(p != cachedObjects.end())
        {
            return p->second;
        }
        else
        {
            return [[[self class] alloc] initWithCppObject:std::move(cppObject)];
        }
    }
}

-(void) dealloc {
    assert(_cppObject != nullptr);
    @synchronized([ICELocalObject class])
    {
        cachedObjects.erase(_cppObject.get());
        _cppObject = nullptr;
    }
}

@end