blob: 2c808c69a0393568b62ccc34f77e64d1b9234fb9 [file] [log] [blame]
mark@chromium.orgde9c22c2009-03-24 00:15:29 +09001// Copyright (c) 2009 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#ifndef BASE_SCOPED_NSOBJECT_H_
6#define BASE_SCOPED_NSOBJECT_H_
7
8#import <Foundation/Foundation.h>
mark@chromium.org582c1dd2009-03-24 00:54:43 +09009#include "base/basictypes.h"
mark@chromium.orgde9c22c2009-03-24 00:15:29 +090010
11// scoped_nsobject<> is patterned after scoped_ptr<>, but maintains ownership
12// of an NSObject subclass object. Style deviations here are solely for
mark@chromium.org582c1dd2009-03-24 00:54:43 +090013// compatibility with scoped_ptr<>'s interface, with which everyone is already
mark@chromium.orgde9c22c2009-03-24 00:15:29 +090014// familiar.
15//
16// When scoped_nsobject<> takes ownership of an object (in the constructor or
17// in reset()), it takes over the caller's existing ownership claim. The
mark@chromium.orgdaef2832009-03-24 04:21:18 +090018// caller must own the object it gives to scoped_nsobject<>, and relinquishes
19// an ownership claim to that object. scoped_nsobject<> does not call
20// -retain.
mark@chromium.orgde9c22c2009-03-24 00:15:29 +090021template<typename NST>
22class scoped_nsobject {
23 public:
24 typedef NST* element_type;
25
26 explicit scoped_nsobject(NST* object = nil)
27 : object_(object) {
28 }
29
30 ~scoped_nsobject() {
31 [object_ release];
32 }
33
34 void reset(NST* object = nil) {
mark@chromium.orgdaef2832009-03-24 04:21:18 +090035 [object_ release];
36 object_ = object;
mark@chromium.orgde9c22c2009-03-24 00:15:29 +090037 }
38
39 bool operator==(NST* that) const {
40 return object_ == that;
41 }
42
43 bool operator!=(NST* that) const {
44 return object_ != that;
45 }
46
47 operator NST*() const {
48 return object_;
49 }
50
51 NST* get() const {
52 return object_;
53 }
54
55 void swap(scoped_nsobject& that) {
56 NST* temp = that.object_;
57 that.object_ = object_;
58 object_ = temp;
59 }
60
61 // scoped_nsobject<>::release() is like scoped_ptr<>::release. It is NOT
62 // a wrapper for [object_ release]. To force a scoped_nsobject<> object to
63 // call [object_ release], use scoped_nsobject<>::reset().
64 NST* release() {
65 NST* temp = object_;
66 object_ = nil;
67 return temp;
68 }
69
70 private:
71 NST* object_;
72
73 DISALLOW_COPY_AND_ASSIGN(scoped_nsobject);
74};
75
76#endif // BASE_SCOPED_NSOBJECT_H_