Question

Since in projects with automatic reference counting NSString * aString; means implicitly NSString * __strong aString;. Does it also count for the parameters and return types?

Is

- (NSString *)doubleString:(NSString *)aString {
    return [NSString stringWithFormat:@"%@%@", aString, aString];
}

the same compiled code as

- (NSString * __strong)doubleString:(NSString * __strong)aString {
    return [NSString stringWithFormat:@"%@%@", aString, aString];
}

and in every similar method?

Was it helpful?

Solution

Short answer: Yes. Both variants produce the same compiled code, as can be verified by "Product -> Perform Action... -> Assemble ..." from the Xcode menu.

Longer answer: (The following references and citations are from the Clang/ARC documentation.)

Your question about the return value. According to "4 Ownership qualification", qualifiers like __strong and __weak apply to locations in memory where a pointer to an object is stored, and they specify the semantics when loading from or storing to an lvalue (4.2 Semantics).

The return value of a method is not such a location in memory (it is not an lvalue), therefore the concept of ownership qualification does not apply here.

It makes not differences if the method is declared as returning (NSString * __weak) or (NSString * __strong), there is no difference in the compiled code.

A slightly different question is whether the caller owns the returned object (it has a +1 retain count) or not. This depends by default on the method name, as explained in "3.2.2 Retained return values" and "3.2.3 Unretained return values".

Your question about the parameters. Declaring the parameter as (NSString * __strong) is identical to (NSString *). This can already be seen from the Xcode autocompletion (where the "__strong" qualifier is not shown), but also from the generated Assembly code.

This does not mean that arguments are retained when calling a method. By default, they are not, as explained in "3.2 Retainable object pointers as operands and arguments".

If an parameter is declared as __weak, it seems (from the Assembly code) that a temporary weak reference is created in the method, i.e.

- (NSString *) doubleString:(NSString * __weak)aString {
    return [NSString stringWithFormat:@"%@%@", aString, aString];
}

is essentially the same as

- (NSString *) doubleString:(NSString *)aString {
    NSString *__weak wString = aString;
    return [NSString stringWithFormat:@"%@%@", wString, wString];
}

But I was not able to find a definite reference for this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top