BookmarkManager: Fix 'new folder text field size changes on clicking it' issue.
[chromium-blink-merge.git] / ios / web / weak_nsobject_counter.mm
blob3c23a397a8f64454e0c4df429706a4b33c7f92bb
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;
20 @end
22 @implementation CRBWeakNSObjectDeallocationObserver {
23   linked_ptr<NSUInteger> _counter;
26 - (instancetype)initWithSharedCounter:(const linked_ptr<NSUInteger>&)counter
27                    objectToBeObserved:(id)object {
28   self = [super init];
29   if (self) {
30     DCHECK(counter.get());
31     DCHECK(object);
32     _counter = counter;
33     objc_setAssociatedObject(
34         object,
35         reinterpret_cast<const void*>(_counter.get()),  // The key.
36         self, OBJC_ASSOCIATION_RETAIN);
37     (*_counter)++;
38   }
39   return self;
42 - (instancetype)init {
43   NOTREACHED();
44   return nil;
47 - (void)dealloc {
48   DCHECK(_counter.get());
49   (*_counter)--;
50   _counter.reset();
51   [super dealloc];
54 @end
56 namespace web {
58 WeakNSObjectCounter::WeakNSObjectCounter() : counter_(new NSUInteger(0)) {
61 WeakNSObjectCounter::~WeakNSObjectCounter() {
62   DCHECK(CalledOnValidThread());
65 void WeakNSObjectCounter::Insert(id object) {
66   DCHECK(CalledOnValidThread());
67   DCHECK(object);
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());
76   return *counter_;
79 }  // namespace web