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 // Used for observing the objects tracked in the WeakNSObjectCounter. This
13 // object will be dealloced when the tracked object is dealloced and will
14 // notify the shared counter.
15 @interface CRBWeakNSObjectDeallocationObserver : NSObject
16 // Designated initializer. |object| cannot be nil. It registers self as an
17 // associated object to |object|.
18 - (instancetype)initWithSharedCounter:(const linked_ptr<NSUInteger>&)counter
19 objectToBeObserved:(id)object;
22 @implementation CRBWeakNSObjectDeallocationObserver {
23 linked_ptr<NSUInteger> _counter;
26 - (instancetype)initWithSharedCounter:(const linked_ptr<NSUInteger>&)counter
27 objectToBeObserved:(id)object {
30 DCHECK(counter.get());
33 objc_setAssociatedObject(
35 reinterpret_cast<const void*>(_counter.get()), // The key.
36 self, OBJC_ASSOCIATION_RETAIN);
42 - (instancetype)init {
48 DCHECK(_counter.get());
58 WeakNSObjectCounter::WeakNSObjectCounter() : counter_(new NSUInteger(0)) {
61 WeakNSObjectCounter::~WeakNSObjectCounter() {
62 DCHECK(CalledOnValidThread());
65 void WeakNSObjectCounter::Insert(id object) {
66 DCHECK(CalledOnValidThread());
68 // Create an associated object and register it with |object|.
69 base::scoped_nsobject<CRBWeakNSObjectDeallocationObserver> observingObject(
70 [[CRBWeakNSObjectDeallocationObserver alloc]
71 initWithSharedCounter:counter_ objectToBeObserved:object]);
74 NSUInteger WeakNSObjectCounter::Size() const {
75 DCHECK(CalledOnValidThread());