Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between CFString and NSString? [duplicate]

I am not getting the differences between CFString and NSString in iOS. Can anyone suggest links or proper answers for this. Thanks in advance.

like image 727
user2533604 Avatar asked Aug 16 '13 13:08

user2533604


People also ask

What is CFString?

Overview. The CFStringRef type refers to a CFString object, which “encapsulates” a Unicode string along with its length. CFString is an opaque type that defines the characteristics and behavior of CFString objects.

What is the difference between NSString and string?

NSString is class and String is struct , I understand but NSString is an reference type ,how it is working inside struct.


2 Answers

NSString is the Foundation counterpart of CFString. This means that they have the exactly the same memory layout in memory.

The reason behind this architecture is historical and goes back to the "collision" between NeXTSTEP and MacOS 9.

Thanks to the toll-free bridging mechanism many CF objects have an interchangeable NS counterpart (other examples are CFArray/NSArray, CFData/NSData, ...) so from a practical point of you can think of them as the same thing.

Here's a nice write-up on the topic: http://ridiculousfish.com/blog/posts/bridge.html

As extra goodie here's my answer on how to perform bridging in ARC environments: NSString to CFStringRef and CFStringRef to NSString in ARC?

like image 172
Gabriele Petronella Avatar answered Oct 02 '22 18:10

Gabriele Petronella


EDIT : This answer is for non-ARC environment.

As per iOS developer library :

CFString is “toll-free bridged” with its Cocoa Foundation counterpart, NSString. This means that the Core Foundation type is interchangeable in function or method calls with the bridged Foundation object. Therefore, in a method where you see an NSString * parameter, you can pass in a CFStringRef, and in a function where you see a CFStringRef parameter, you can pass in an NSString instance. This also applies to concrete subclasses of NSString. See “Toll-Free Bridged Types” for more information on toll-free bridging

Convert NSString to CFStringRef:

NSString *test = @"Everyone is created equal.";
CFStringRef string =  (CFStringRef) test;

Convert CFStringRef to NSString:

NSString *backToNSString =  (NSString *) string;
like image 42
Vineet Singh Avatar answered Oct 02 '22 16:10

Vineet Singh