bw1024
bw1024

Reputation: 1158

Clarification for ARC code in Apple sample

The standard Xcode 5 OpenGLES template example creates an application that includes the following as part of the shader loading code:

const GLchar *source;

source = (GLchar *)[[NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil] UTF8String]; // load file

...

glShaderSource(*shader, 1, &source, NULL);

After wading through Clang LLVM ARC, I would have expected the NSString object created from the contents of the file to "get released at the end of the full-expression containing it". However, then UTF8String method is declared in NSString.h as:

- (__strong const char *)UTF8String;

Does this mean that ARC is smart enough to figure out that the NSString object should be retained until source goes out of scope? Or am I way off track?

Upvotes: 0

Views: 120

Answers (2)

CRD
CRD

Reputation: 53000

In the current Xcode 5.0.02/Clang 4.2 compiler UTF8String is declared as:

- (__strong const char *)UTF8String NS_RETURNS_INNER_POINTER;

This indicates that its return value is a non-reference counted pointer into the object it is applied to and ARC will extend the life of that object as required to keep the pointer valid. See the Interior Pointers section of the same reference you quoted. So the answer to your question:

Does this mean that ARC is smart enough to figure out that the NSString object should be retained until source goes out of scope?

is yes, as long as the attribute it specified - it cannot figure that part out itself.

Upvotes: 2

Bryan Chen
Bryan Chen

Reputation: 46598

[NSString stringWithContentsOfFile] returns a autoreleased object, which means it is alive until next runloop i.e. after current method exit

Upvotes: 2

Related Questions