Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / ios / web / weak_nsobject_counter.mm
blobedcf01ae1ac7f34c66b8e49371449a1f499a38c9
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #import "ios/web/weak_nsobject_counter.h"
7 #import <objc/runtime.h>
9 #include "base/logging.h"
10 #import "base/mac/scoped_nsobject.h"
12 namespace {
13 // The key needed for objc_setAssociatedObject. Any value will do, because the
14 // address is the key.
15 const char kObserverAssociatedObjectKey = 'h';
18 // Used for observing the objects tracked in the WeakNSObjectCounter. This
19 // object will be dealloced when the tracked object is dealloced and will
20 // notify the shared counter.
21 @interface CRBWeakNSObjectDeallocationObserver : NSObject
22 // Designated initializer. |object| cannot be nil. It registers self as an
23 // associated object to |object|.
24 - (instancetype)initWithSharedCounter:(const linked_ptr<NSUInteger>&)counter
25                    objectToBeObserved:(id)object;
26 @end
28 @implementation CRBWeakNSObjectDeallocationObserver {
29   linked_ptr<NSUInteger> _counter;
32 - (instancetype)initWithSharedCounter:(const linked_ptr<NSUInteger>&)counter
33                    objectToBeObserved:(id)object {
34   self = [super init];
35   if (self) {
36     DCHECK(counter.get());
37     DCHECK(object);
38     _counter = counter;
39     objc_setAssociatedObject(object, &kObserverAssociatedObjectKey, self,
40                              OBJC_ASSOCIATION_RETAIN);
41     (*_counter)++;
42   }
43   return self;
46 - (instancetype)init {
47   NOTREACHED();
48   return nil;
51 - (void)dealloc {
52   DCHECK(_counter.get());
53   (*_counter)--;
54   _counter.reset();
55   [super dealloc];
58 @end
60 namespace web {
62 WeakNSObjectCounter::WeakNSObjectCounter() : counter_(new NSUInteger(0)) {
65 WeakNSObjectCounter::~WeakNSObjectCounter() {
66   DCHECK(CalledOnValidThread());
69 void WeakNSObjectCounter::Insert(id object) {
70   DCHECK(CalledOnValidThread());
71   DCHECK(object);
72   // Create an associated object and register it with |object|.
73   base::scoped_nsobject<CRBWeakNSObjectDeallocationObserver> observingObject(
74       [[CRBWeakNSObjectDeallocationObserver alloc]
75           initWithSharedCounter:counter_ objectToBeObserved:object]);
78 NSUInteger WeakNSObjectCounter::Size() const {
79   DCHECK(CalledOnValidThread());
80   return *counter_;
83 }  // namespace web