| OLD | NEW |
| (Empty) | |
| 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. |
| 4 |
| 5 #import "ios/web/weak_nsobject_counter.h" |
| 6 |
| 7 #import <objc/runtime.h> |
| 8 |
| 9 #include "base/logging.h" |
| 10 #import "base/mac/scoped_nsobject.h" |
| 11 |
| 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'; |
| 16 } |
| 17 |
| 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 |
| 27 |
| 28 @implementation CRBWeakNSObjectDeallocationObserver { |
| 29 linked_ptr<NSUInteger> _counter; |
| 30 } |
| 31 |
| 32 - (instancetype)init { |
| 33 NOTREACHED(); |
| 34 return nil; |
| 35 } |
| 36 |
| 37 - (instancetype)initWithSharedCounter:(const linked_ptr<NSUInteger>&)counter |
| 38 objectToBeObserved:(id)object { |
| 39 self = [super init]; |
| 40 if (self) { |
| 41 DCHECK(counter.get()); |
| 42 DCHECK(object); |
| 43 _counter = counter; |
| 44 objc_setAssociatedObject(object, &kObserverAssociatedObjectKey, self, |
| 45 OBJC_ASSOCIATION_RETAIN); |
| 46 (*_counter)++; |
| 47 } |
| 48 return self; |
| 49 } |
| 50 |
| 51 - (void)dealloc { |
| 52 DCHECK(_counter.get()); |
| 53 (*_counter)--; |
| 54 _counter.reset(); |
| 55 [super dealloc]; |
| 56 } |
| 57 |
| 58 @end |
| 59 |
| 60 namespace web { |
| 61 |
| 62 WeakNSObjectCounter::WeakNSObjectCounter() : counter_(new NSUInteger(0)) { |
| 63 } |
| 64 |
| 65 WeakNSObjectCounter::~WeakNSObjectCounter() { |
| 66 DCHECK(CalledOnValidThread()); |
| 67 } |
| 68 |
| 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]); |
| 76 } |
| 77 |
| 78 NSUInteger WeakNSObjectCounter::Size() const { |
| 79 DCHECK(CalledOnValidThread()); |
| 80 return *counter_; |
| 81 } |
| 82 |
| 83 } // namespace web |
| OLD | NEW |