CFStringRef

From REALbasicWiki

Jump to: navigation, search

The CFStringRef datatype is used when declaring into the Carbon and Cocoa frameworks. CFString objects are reference-counted, and it is important to understand that CFStrings are always released by the REALbasic framework when a CFStringRef variable or property is destroyed. If you assign to a CFStringRef using a Core Foundation "Get" function, then you should call CFRetain to increment the reference count.

CFString is toll-free bridged with its Cocoa counterpart NSString, so CFStringRef can be used when declaring Cocoa functions.

[edit] Nil v. ""

A nil CFString is not the same as the non-nil CFString "". You can create either in REALbasic.

dim s as CFString = nil
dim t as CFString = ""

A nil CFStringRef is a null pointer. A CFStringRef pointing to the empty string "" is a non-nil pointer to a CFString object.

Unfortunately, it is currently impossible to test whether a CFStringRef is nil (as of REALbasic 2007r5; a feedback report has been filed). In situations where it matters, you should attempt to get a Ptr instead of a CFStringRef; how to convert between a non-nil Ptr and a CFStringRef is discussed below.



[edit] Conversion To and From String

REALbasic converts between String and CFStringRef. You can create a CFStringRef by assigning a String variable, property, or constant.

dim s as CFStringRef = "foo"

And you can assign a CFStringRef to a String.

dim t as String = s


[edit] Conversion To and From Ptr

REALbasic does not support conversion between CFStringRef and Ptr, but the need to do so arises from time to time. Structures cannot contain CFStringRef fields, so to declare a Mac OS structure containing a CFStringRef field, you need to declare the field to be of type Ptr and do the conversion yourself.

A trick for doing so is to use the Core Foundation function CFRetain.

soft declare function CFRetain lib "Carbon.framework" (cf as CFStringRef) as Ptr

Using this declaration, you can convert from CFStringRef to Ptr.

dim title as CFStringRef = "foo"
dim p as Ptr = CFRetain(title)

By changing the declared variable types, you can also convert a Ptr to a CFStringRef. Keep in mind that CFRetain increases the reference count of a CFString, so you may need to call CFRelease to get the reference count right.


You can also convert from Ptr to CFStringRef using CFRetain by changing its declaration.

soft declare function CFRetain lib "Carbon.framework" (cf as Ptr) as CFStringRef

Beware that passing a nil Ptr will result in a crash.

Personal tools
related