1 // Copyright (c) 2008 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_FOUNDATION_UTILS_MAC_H_
6 #define BASE_FOUNDATION_UTILS_MAC_H_
7
8 #include <CoreFoundation/CoreFoundation.h>
9 #import <Foundation/Foundation.h>
10
11 // CFTypeRefToNSObjectAutorelease transfers ownership of a Core Foundation
12 // object (one derived from CFTypeRef) to the Foundation memory management
13 // system. In a traditional managed-memory environment, cf_object is
14 // autoreleased and returned as an NSObject. In a garbage-collected
15 // environment, cf_object is marked as eligible for garbage collection.
16 //
17 // This function should only be used to convert a concrete CFTypeRef type to
18 // its equivalent "toll-free bridged" NSObject subclass, for example,
19 // converting a CFStringRef to NSString.
20 //
21 // By calling this function, callers relinquish any ownership claim to
22 // cf_object. In a managed-memory environment, the object's ownership will be
23 // managed by the innermost NSAutoreleasePool, so after this function returns,
24 // callers should not assume that cf_object is valid any longer than the
25 // returned NSObject.
CFTypeRefToNSObjectAutorelease(CFTypeRef cf_object)26 static inline id CFTypeRefToNSObjectAutorelease(CFTypeRef cf_object) {
27 // When GC is on, NSMakeCollectable marks cf_object for GC and autorelease
28 // is a no-op.
29 //
30 // In the traditional GC-less environment, NSMakeCollectable is a no-op,
31 // and cf_object is autoreleased, balancing out the caller's ownership claim.
32 //
33 // NSMakeCollectable returns nil when used on a NULL object.
34 return [NSMakeCollectable(cf_object) autorelease];
35 }
36
37 #endif // BASE_FOUNDATION_UTILS_MAC_H_
38