I have an NSError ** stored in an array (so I can get it as such array[0]). I'm trying to cast it into a variable:
NSError * __autoreleasing *errorPointer = (NSError * __autoreleasing *)array[0];
so I can access the underlying object as *errorPointer.
However, Xcode complains that Cast of an Objective-C pointer to 'NSError *__autoreleasing *' is disallowed with ARC. Is there any way to get to this object without turning off ARC?
Neither that stub:withBlock: method or any of its supporting infrastructure could be simply stuffing a double pointer into an NSArray. The array won't take non-objects, and a pointer to an object is not an object. There's something else going on.
This obviously requires some digging into the code to figure out. Where does the value get put into the array? That's in -[KWStub processInvocation:], and it's done apparently using a method added to NSInvocation by OCMock, getArgumentAtIndexAsObject:. In that method, the invocation uses a switch to check the type of the argument that is requested, and boxes it up if necessary.
The relevant case here is the last one, where the argument type is ^, meaning "pointer". This sort of argument is wrapped up in an NSValue; therefore, the array recieved by your Block actually contains, not the double pointer itself, but an NSValue representing the outer pointer. You just need to unbox it.
That should look like this:
NSValue * errVal = array[1];
NSError * __autoreleasing * errPtr = (NSError * __autoreleasing *)[errVal pointerValue];
Related
I noticed this pattern in Apple functions which return errors
error:(NSError *__autoreleasing *)outError
I understand the meaning, that it's pointer to pointer, used to carry out the result (using just * would change only the local copied variable, but not the outside one) but I'm concerned about the:
__autoreleasing
What happens if I leave it out? Do I get a leak? Why is it necessary?
You don't have to explicitly specify __autoreleasing when defining a function that
returns an object, for example
-(BOOL)doSomething:(NSError **)error;
The ARC compiler automatically inserts the __autoreleasing. This is explained in
the Clang/ARC documentation:
4.4.2 Indirect parameters
If a function or method parameter has type T*, where T is an
ownership-unqualified retainable object pointer type, then:
if T is const-qualified or Class, then it is implicitly qualified with
__unsafe_unretained;
otherwise, it is implicitly qualified with __autoreleasing.
The Xcode code completion
also knows about that and displays (NSError *__autoreleasing *)error.
When calling such a function the ARC compiler also automatically does
"the right thing", so you can just call
NSError *error;
BOOL success = [self doSomething:&error];
As explained in the "Transitioning to ARC Release Notes", the compiler inserts a temporary
__autoreleasing variable:
NSError *error;
NSError * __autoreleasing tmp = error;
BOOL success = [self doSomething:&tmp];
error = tmp;
(For the gory details you can read 4.3.4 "Passing to an out parameter by writeback" in
the Clang/ARC documentation.)
I'm trying to implement the countByEnumeratingWithState:objects:count: method from the NSFastEnumeration protocol on a custom class.
So far I have it iterating through my objects correctly, but the objects that are returned aren't Objective-C objects but rather the core foundation equivalents.
Here's the part of the code that sets the state->itemsPtr:
MyCustomCollection.m
- (NSUInteger) countByEnumeratingWithState: (NSFastEnumerationState *)state
objects: (id __unsafe_unretained *)buffer
count: (NSUInteger)bufferSize {
// ... skip details ...
NSLog(#"Object inside method: %#", someObject);
state->itemsPtr = (__unsafe_unretained id *)(__bridge void *)someObject;
// ... skip details ...
}
Then I call the 'for..in' loop somewhere else on like this
SomeOtherClass.m
MyCustomCollection *myCustomCollection = [MyCustomCollection new];
[myCustomCollection addObject:#"foo"];
for (id object in myCustomCollection) {
NSLog(#"Object in loop: %#", object);
}
The console output is:
Object inside method: foo
Object in loop: __NSCFConstantString
As you can see, inside the NSFastEnumeration protocol method the object prints fine, but as soon as it gets cast to id __unsafe_unretained * I lose the original Objective-C corresponding class.
To be honest I'm not quite sure how the (__unsafe_unretained id *)(__bridge void *) casting works in this case. The (__unsafe_unretained id *) seems to cast to match the right type itemsPtr needs. The (__bridge void *) seems to cast to a pointer of type void with __bridge used to bridge the obj-c world to the CF world. As per the llvm docs, for __bridge:
There is no transfer of ownership, and ARC inserts no retain operations
Is that correct?
From my understanding __NSCFConstantString is just the core foundation equivalent of NSString. I also understand that with ARC you need to bridge from Objective-C objects to CoreFoundation equivalents because ARC doesn't know how to manage the memory of the latter.
How can I get this working so that the objects in my 'for..in' loop are of the original type?
Also note that in this case I'm adding NSStrings to my collection but in theory it should support any object.
UPDATE
Rob's answer is on the right track, but to test that theory I changed the for loop to this:
for (id object in myCustomCollection) {
NSString *stringObject = (NSString *)object;
NSLog(#"String %# length: %d", stringObject, [stringObject length]);
}
In theory that should work since the objects are equivalent but it crashes with this error:
+[__NSCFConstantString length]: unrecognized selector sent to class
It almost looks like the objects returned in the for loop are classes and not instances. Something else might be wrong here... Any thoughts on this?
UPDATE 2 : SOLUTION
It's as simple as this: (thanks to CodaFi
state->itemsPtr = &someObject;
You're incorrectly casting someObject. What you meant is:
state->itemsPtr = (__unsafe_unretained id *)(__bridge void *)&someObject;
(Let's get rid of those awful casts as well)
state->itemsPtr = &someObject;
Without the address-of, your variable is shoved into the first pointer, which is dereferenced in the loop. When it's dereferenced (basically, *id), you get the underlying objc_object's isa class pointer rather than an object. That's why the debugger prints the string's value inside the enumerator call, and the class of the object inside the loop, and why sending a message to the resulting pointer throws an exception.
Your code is fine the way it is. Your debug output is revealing an implementation detail.
NSString is toll-free-bridged with CFString. This means that you can treat any NSString as a CFString, or vice versa, simply by casting the pointer to the other type.
In fact, under the hood, compile-time constant strings are instances of the type __NSCFConstantString, which is what you're seeing.
If you put #"hello" in your source code, the compiler treats it as a NSString * and compiles it into an instance of __NSCFConstantString.
If you put CFSTR("hello") in your source code, the compiler treats it as a CFStringRef and compiles it into an instance of __NSCFConstantString.
At run-time, there is no difference between these objects in memory, even though you used different syntax to create them in your source code.
As per Transitioning to ARC Release Notes:
__autoreleasing is used to denote arguments that are passed by reference (id *) and are autoreleased on return.
For example:
-(BOOL)performOperationWithError:(NSError * __autoreleasing *)error;
But what are the advantages of the above comparing to:
-(BOOL)performOperationWithError:(NSError * __strong *)error;
Update:
Several answers refer to the temp var trick compiler does to deal with the mismatch between var and argument as the advantage of __autoreleasing. I don't see why compiler can not do the same trick for __strong argument. I mean, for a __weak var and __strong argument, compiler can similarly do this:
NSError * __weak error;
NSError * __strong tmp = error;
BOOL OK = [myObject performOperationWithError:&tmp];
error = tmp;
if (!OK) {
// Report the error.
}
Compiler knows -(BOOL)performOperationWithError:(NSError * __strong *)error; returns a strong reference(+1) so it handles it just like any new-family method. Since tmp lives in the same scope as error, compiler can reasonably keep it alive as long as error so the __weak reference(error) is now supported by a __strong reference(tmp) and will not be nullified until the end of the scope.
tl;dr
Implicitly converting a __weak object to a __strong object in this case would alter the semantic of the program, something that a compiler should never do.
The scenario
Let's take an example
NSError *error;
BOOL success = [myObject performOperationWithError:&error];
if (!success) {
// Report the error
}
In such a case the error local variable is automatically inferred by ARC as __strong.
At the same time the error argument of
-(BOOL)performOperationWithError:(NSError * __autoreleasing *)error;
is of type NSError * __autoreleasing *.
Please note that in any case ARC will infer parameters passed by reference (id *) as being of type id __autoreleasing *, so the above signature is equivalent to
-(BOOL)performOperationWithError:(NSError **)error;
under ARC.
Therefore we have a mismatch since we are passing a __strong annotated variable to a method expecting an __autoreleasing argument.
Under the hood
In our example then the compiler will address such mismatch by creating a local __autoreleasing tmp variable.
The code becomes
NSError * __strong error;
NSError * __autoreleasing tmp = error;
BOOL success = [myObject performOperationWithError:&tmp];
error = tmp;
if (!success) {
// Report the error.
}
An alternative
Let's now pretend that we can change the signature of performOperationWithError:.
If we want to avoid the "compiler trick" which uses the tmp variable, we can declare our signature as
-(BOOL)performOperationWithError:(NSError * __strong *)error;
We have a __strong variable and we are now passing it to a method expecting a __strong argument, so we just eliminated the mismatch.
Looks good, why not always declare __strong arguments?
One reason is that declaring the argument as __autoreleasing will make the method to accept even a __weak reference.
It does not make much sense in the current example, but there could be cases in which we'd like to pass a __weak variable by reference and declaring __autoreleasing (or leaving the ARC to infer it) will allow us to do so.
ARC will apply the same trick seen above, creating a __autoreleasing tmp variable.
Conclusion
The mechanism presented so far goes under the name of pass-by-writeback.
Such mechanism has been designed to work with __autoreleasing, __strong and __weak variables, so that the programmer can safely rely on the type inference made by the compiler and not care too much about annotating variables around.
Declaring a id __strong * argument may make sense in some cases, but in general it could lead to unexpected errors generated by the compiler.
My advice here is: "let the compiler do his magic and you'll be good"
Update
I don't see why compiler can not do the same trick for __strong argument.
Telling the compiler to handle in an __autoreleasing fashion the management of either a __strong or __weak variable it's ok since it basically means: "Please, compiler, do the right thing automatically".
That's why the trick seen above will work without issues.
On the other hand, if you declare a variable as __weak you presumably have a good reason for doing so and the last thing you want is to have it implicitly retained when you clearly specified otherwise. That would radically change the semantic of the piece of code you've written, therefore the compiler won't do that (thank God!).
In other words
__weak --> __autoreleasing good
__strong --> __autoreleasing good
__weak <--> __strong wrong!
The only advantage is, as you said, that the object is autoreleased on return. So without ARC it's the same as sending retain and autorelease. In C every variable passed as argument is copied, so this doesn't influence what will be done with the original pointer, but just with the copied pointer.
An example of advantage could be this, let's say the argument isn't __autoreleasing:
-(BOOL)performOperationWithError:(NSError * __strong *)error;
So I call the method passing a weak reference:
NSError* __weak error;
[object performSelectorWithError: &error];
What happens here? The copied argument isn't autoreleased on return, so when the method returns error is nil. If instead the method was this one:
-(BOOL)performOperationWithError:(NSError * __autoreleasing *)error;
This case the error had still a retain count of 1, but it was autoreleased, so it wasn't nil and could have been used inside the pool.
The other reason which I haven't seen mentioned is to follow Cocoa conventions so that ARC code can properly interoperate with non-ARC code.
I'm trying to complete the puzzle.
__strong is the default for all Objective-C retainable object pointers like NSObject, NSString, etc.. It's a strong reference. ARC balances it with a -release at the end of the scope.
__unsafe_unretained equals the old way. It's used for a weak pointer without retaining the retainable object.
__weak is like __unsafe_unretained except that it's an auto-zeroing weak reference meaning that the pointer will be set to nil as soon as the referenced object is deallocated. This eliminates the danger of dangling pointers and EXC_BAD_ACCESS errors.
But what exactly is __autoreleasing good for? I'm having a hard time finding practical examples on when I need to use this qualifier. I believe it's only for functions and methods which expect a pointer-pointer such as:
- (BOOL)save:(NSError**);
or
NSError *error = nil;
[database save:&error];
which under ARC has to be declared this way:
- (BOOL)save:(NSError* __autoreleasing *);
But this is too vague and I'd like to fully understand why. The code snippets I find place the __autoreleasing inbetween the two stars, which looks weird to me. The type is NSError** (a pointer-pointer to NSError), so why place __autoreleasing inbetween the stars and not simply in front of NSError**?
Also, there might be other situations in which I must rely on __autoreleasing.
You're right. As the official documentation explains:
__autoreleasing to denote arguments that are passed by reference (id *) and are autoreleased on return.
All of this is very well explained in the ARC transition guide.
In your NSError example, the declaration means __strong, implicitly:
NSError * e = nil;
Will be transformed to:
NSError * __strong error = nil;
When you call your save method:
- ( BOOL )save: ( NSError * __autoreleasing * );
The compiler will then have to create a temporary variable, set at __autoreleasing. So:
NSError * error = nil;
[ database save: &error ];
Will be transformed to:
NSError * __strong error = nil;
NSError * __autoreleasing tmpError = error;
[ database save: &tmpError ];
error = tmpError;
You may avoid this by declaring the error object as __autoreleasing, directly.
Following up on Macmade's answer and Proud Member's follow up question in the comments, (would have also posted this as a comment but it exceeds the max character count):
Here is why the variable qualifier of __autoreleasing is placed between the two stars.
To preface, the correct syntax for declaring an object pointer with a qualifier is:
NSError * __qualifier someError;
The compiler will forgive this:
__qualifier NSError *someError;
but it isn't correct. See the Apple ARC transition guide (read the section that begins "You should decorate variables correctly...").
To address to the question at hand: A double pointer cannot have an ARC memory management qualifier because a pointer that points to a memory address is a pointer to a primitive type, not a pointer to an object. However, when you declare a double pointer, ARC does want to know what the memory management rules are for the second pointer. That's why double pointer variables are specified as:
SomeClass * __qualifier *someVariable;
So in the case of a method argument that is a double NSError pointer, the data type is declared as:
- (BOOL)save:(NSError* __autoreleasing *)errorPointer;
which in English says "pointer to an __autoreleasing NSError object pointer".
The definitive ARC specification says that
For __autoreleasing objects, the new pointer is retained, autoreleased, and stored into the lvalue using primitive semantics.
So for example, the code
NSError* __autoreleasing error = someError;
actually gets converted to
NSError* error = [[someError retain] autorelease];
... which is why it works when you have a parameter NSError* __autoreleasing * errorPointer, the called method will then assign the error to *errorPointer and the above semantics will kick in.
You could use __autoreleasing in a different context to force an ARC object into the autorelease pool, but that's not terribly useful since ARC only seems to use the autorelease pool at method return and already handles that automatically.
To be short: this is only for compatibility with MRC.
Apple have made agreement that in own libraries objects returned by ** are always autoreleased. So ARC code will work fine with old binaries (for example if you have deployment target iOS 4) and vise versa MRC code will work fine with ARC binaries.
So in conclusion:
You should never use __autoreleasing: compiler will automatically add it where needed
If you are not going to support MRC code, then you should use * __strong * everywhere. It will save from crashes of family:
#autoreleasingpool {
*autorelesingOut = [#"crash maker" mutableCopy];//NSString * __autoreleasing *autorelesingOut;
*strongOut = [#"it's ok" mutableCopy];//NSString * __strong *strongOut;
//App will crash if autorelesingOut will be referenced outside of this autoreleasepool
}
Sometimes I encounter code that has *, sometimes **. Can anyone explain what they mean in Objective C? (I used to be a Java programmer, with experience in C/C++.)
The * denotes that you are using a pointer to a variable, and is most commonly used to store a reference to an Objective-C object, objects which can only live on the heap and not the stack.
Pointers are not a part of Objective-C exclusively, but rather a feature of C (and therefore its derived languages, of which Objective-C is one of them).
If you are questioning the difference between * and **, the first denotes a pointer, whereas the second denotes a pointer to a pointer; the advantage of the latter to the former is that when passing in an object using ** in a method parameter, the method can then change this parameter and the new value is accessible in the calling method.
Perhaps the most common use of ** in Cocoa is when using NSError objects. When a method is called that can return an NSError object on failure, the method signature would look something like this:
- (id)someMethodThatUsesObject:(id)object error:(NSError**)error;
What this means is that the calling function can pass in a pointer to an NSError object, but someMethodThatUsesObject: can change the value of error to another NSError object if it needs to, which can then be accessed by the calling method.
This is often used as a workaround for the fact that functions can only return one value.
A * in Objective-C means exactly the same as in C; and you'll usually see it (or not) in these situations:
// Method signatures:
// Here the asterisk (*) shows that you have a pointer to an NSString instance.
+ (NSString *)stringWithString:(NSString *)aString;
// Method signatures, part two:
// Here the double asterisk (**) signifies that you should pass in a pointer
// to an area of memory (NSError *) where outError can be written.
- (BOOL)writeToURL:(NSURL *) atomically:(BOOL) error:(NSError **)outError;
// Method signatures make for good examples :)
// Here the asterisk is hidden; id is a typedef for void *; and it signifies that
// a pointer to some object of an indeterminate class will be returned
- (id)init;
// And a forth example to round it all out: C strings!
// Here the asterisk signifies, you guessed it, a pointer! This time, it's a
// pointer to the first in a series of const char; terminated by a \0, also known
// as a C string. You probably won't need to work with this a lot.
- (const char *)UTF8String;
// For a bit of clarity, inside example two, the outError is used as follows:
// Here the asterisk is used to dereference outError so you can get at and write
// to the memory it points to. You'd pass it in with:
// NSError *anError;
// [aString writeToURL:myURL atomically:YES error:&anError];
- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atom error:(NSError **)outError {
// do some writing, and if it went awry:
if (outError != NULL)
*outError = [NSError errorWithName:#"NSExampleErrorName"];
return NO;
}