I am having issues in code when calling dispatch_async. I think that issue is due to ARC reclaiming the object, before it is used in a block, as the method that dispatches it finishes.
- (void) method:(SomeClass *) someClass {
// local variable
NSNumber *someValue = someClass.somePropertyOnManagedObject;
dispatch_async(queue, ^() {
/* call some singleton object passing variable
* when access the variable, reference is nil
*/
[[DashboardFacade sharedInstance] someMethod:someValue];
});
}
After having looking through much documentation, I conclude
Block accesses no parameters – nothing to discuss
Block accesses simple type parameters e.g. BOOL, int - these are copied and not a problem
Block accesses parameter of method that dispatched it - I am not sure, but think
that this is ok
Block accesses property of self – as long as self “lives” until the call has finished ok
Block accesses local variable in method that dispatched it
If we use some semaphores such that we wait for the block to return before leaving the method, then all ok
Otherwise variable may have been garbage collected before block can use.
I think that the solution is to use __block modifier such that ARC retains the variable.
My question is
Is the above technically correct, e.g. using __block will resolve the problem and not introduce other problems?
Why can't I find this anywhere on the internet/google?
Is the above technically correct, e.g. using __block will resolve the
problem and not introduce other problems?
Yes it's technically correct, __block, on ARC, allows you to change the variable (in this case to where its pointing, since it's a NSNumber *), that was declared outside the block context.
Why can't I find this anywhere on the internet/google?
I think the problem is not related to this particular place of your code, but something else.
someValue inside the block can be nil only if it is nil after this assignment:
NSNumber *someValue = someClass.somePropertyOnManagedObject;
Blocks retain objects that are being captured by the blocks as a result of those variables being used inside the blocks. And it doesn’t matter if it is self or a local variable from the scope that is visible to the block.
Related
What happens when I declare a static variable inside a block like this?
dispatch_async(dispatch_get_main_queue(), ^{
static NSInteger myNumber;
// do stuff with myNumber
});
What happens the second time this block is triggered?
How can myNumber be still there if the block will deallocate after running?
Is doing this OK? I mean will this practice cause any problem, like the block leaking because it is unable to be released?
The block specification does not explicitly mention how static variables within blocks are handled, just that the block body is a compound statement which is just the same as the body of a function. Therefore the semantics are the same as for static variables declared in a function, that is they are variables of global lifetime which are only directly accessible by name within the scope they are declared in.
A block value is constructed each time a block literal (^{...}) is evaluated. This value contains a standard C function pointer to the compiled code of the block body, which like any other compound statement is generated once at compile time.
The answers to your questions just follow from this:
What happens the second time this block is triggered?
Same thing that happens the second time a function with a local static variable is executed, the function body sees the value previously stored in the variable.
How can myNumber be still there if the block will deallocate after running?
Because it is the block value, which includes any associated captured variables, which is deallocated; the compiled code, which includes any static variables, always exists.
Is doing this OK? I mean will this practice cause any problem, like the block leaking because it is unable to be released?
Doing this is the same as doing it within a function. If the static is of Objective-C object type then references stored in it may "leak" - just as with standard global variables. The block value will not be prevented from deallocation unless you store a reference to the block itself (directly or indirectly via a chain of references) in the static variable.
HTH
maybe we can answer using "C" underlying logic.. closure-> blocks -> pointer to std C functions, to "C" static logic occurs-> globals (OMG!)
I'm subclassing AVQueuePlayer, and in my constructor, where I pass the AVPlayerItem's it needs to play, I want to add an observer on the first item to play.
So I'm using the AVPlayer method addBoundaryTimeObserverForTimes:queue:usingBlock:. Proper implementation requires me to call removeTimeObserver: on the "opaque" object that addBoundary method returns.
In order to retain the object for however long is necessary, I declared it as a __block ivar:
#property (nonatomic, copy) __block id obs;
then in my own init method I have:
__block AVPlayer* blockPlayer = self;
_obs = [self addBoundaryTimeObserverForTimes: times
queue:NULL
usingBlock:^{
// Post a notification that I can then act on
[[NSNotificationCenter defaultCenter]
postNotificationName:#"PlaybackStartedNotification"
object:nil];
// Remove the boundary time observer
[blockPlayer removeTimeObserver:_obs]; // Warning here
}];
There's a lot going on here... And although the specific warning comes when I try to remove the time observer, I'm also posting a notification, which I may also change to pass a variable in the object: part. I'm also setting self as the observer...
I've read a lot of other answers on potential solutions (example)
but I haven't really found anything about using block variables.
Is my code unsafe or am I okay?
Edit: I originally mistyped the name of the #property as __block id observer when I indeed meant for it to be __block id obs. The accepted answer thus answered both scenarios! (Awesome!)
(All code typed directly into answer, treat it as pseudo-code and expect there to be minor typos at least!)
You are unfortunately misunderstanding the purpose and behaviour of __block - it is an attribute which only applies to local variables and modifies their lifetime so they can be safely updated by a block. So:
In order to retain the object for however long is necessary, I declared it as a __block ivar:
#property (nonatomic, copy) __block id observer;
is an invalid property declaration, as properties are instance methods usually backed by instance - not local - variables. The current Apple compiler unfortunately just ignores the meaningless __block rather than reporting an error - a bug which has previously caused confusion for SO inquirers (you should submit a bug report to Apple to encourage them to fix it).
Next you write:
__block AVPlayer* blockPlayer = self;
so you can use blockPlayer within your block instead of self in an attempt to avoid a retain cycle. This does not work, indeed it simple adds another (anonymous) object into the cycle... What you need here is a weak reference:
__weak AVPlayer *blockPlayer = self;
Weak references break a cycle, but within the block you must first create a strong reference from them and check it is not NULL - which it will be if the object it weakly references has been destroyed. The code to do this within your block will be something like:
// Remove the boundary time observer if blockPlayer still exists
AVPlayer *strongBlockPlayer = blockPlayer; // obtain strong reference from weak one
if (strongBlockPlayer)
[strongBlockPlayer ...];
Even after these changes you have a bigger problem. In your code you have:
_obs = [self addBoundaryTimeObserverForTimes:times
queue:NULL
usingBlock:^{
...
[blockPlayer removeTimeObserver:_obs];
}];
Here you are attempting to use the value of _obs within your block.
At this point your question becomes unclear, is _obs meant to be a local variable or the property observer? We'll consider both cases:
Local Variable
If _obs is a local variable your code will not work. When a block is created the values of any local variables used by the block are copied into the block itself, so here the value of _obs would be copied. However _obs will not have a valid value at this point, that will only happen after the call to addBoundaryTimeObserverForTimes:queue:usingBlock: returns and the assignment of its return value, which is after the block has been created and passed to the same call...
This problem is similar to defining a local recursive block and has the same solution. If a local variable is declared with the __block attribute, so that its lifetime is modified to match that of any blocks using it and thus those blocks can modify its value, then the value in the local variable is not copied into the block - instead the block gets a reference to the variable which it uses to read/write the variable as needed.
So to make the code work you change it to:
__block id obs = [self addBoundaryTimeObserverForTimes:times
queue:NULL
usingBlock:^{
...
[blockPlayer removeTimeObserver:obs];
}];
In this version:
The local variable obs will be created in such a way that its lifetime is at least as long as your block (we'll skip the details of how the compiler arranges this - they are interesting but not of critical importance);
The block is created with a reference to the variable jobs;
The method addBoundaryTimeObserverForTimes:queue:usingBlock: is called passing it the block;
The method returns and its result is assigned to obs; and
(A little later) the block is invoked, reads obs, and obtains the value stored there after the method call.
Property Reference
If you've made a typo and you intended _obs to be the property observer then the LHS of the assignment should be self.observer and the RHS should be blockPlayer.observer, which allowing for the need for the weak reference would be:
__weak AVPlayer *blockPlayer = self;
self.observer = [self addBoundaryTimeObserverForTimes:times
queue:NULL
usingBlock:^{
...
// Remove the boundary time observer if blockPlayer still exists
AVPlayer *strongBlockPlayer = blockPlayer; // obtain strong reference from weak one
if (strongBlockPlayer)
[strongBlockPlayer removeTimeObserver:strongBlockPlayer.observer];
}];
This will work as by the time the block is called and reads strongBlockPlayer.observer the call to addBoundaryTimeObserverForTimes:queue:usingBlock: block will have returned and the assignment to the property made.
Local Variable vs. Property for obs/observer?
Which of the above two versions, both of which should work, is better? Probably the local variable version as (a) you don't appear to need the property elsewhere and (b) it localises the need for the variable to just the statement, the method call, which needs it, which in turn helps readability and debugging. However that is an opinion and some might disagree - make your own choice!
HTH
I have been using blocks and familiar with the memory management when using self inside blocks in
Non-ARC environment
But I have two specific questions:
1) I understand I can use __block to avoid the retain cycle a retained block which in turn using self can create, like below:
__block MyClass *blockSelf = self;
self.myBlock = ^{
blockSelf.someProperty = abc;
[blockSelf someMethod];
};
This will avoid the retain cycle for sure but I by doing this I have created a scope for self to be released and eventually deallocated by someone else. So when this happen self is gone and blockSelf is pointing to a garbage value. There can be conditions when the block is executed after the self is deallocated, then the block will crash as it is trying to use deallocated instance. How do we can avoid this condition? How do I check if blockSelf is valid when block executes or stop block from executing when self is deallocated.
2) On the similar lines suppose I use block like below:
__block MyClass *blockSelf = self;
self.myBlock = ^{
[blockSelf someMethod:blockSelf.someProperty];
};
// I am taking someProperty in an method argument
-(void) someMethod:(datatype*)myClassProperty
{
myClassProperty = abc;
}
Now there can be situations where self is not released but someProperty is released before someMethod's execution starts (This could happen when there are multiple threads). Even if I do self.someProperty = nil; when it is release, myClassProperty is not nil and pointing to some garbage, hence when someMethod is executed the first line will lead to crash. How do I avoid this?
This is the same issue as non-zeroing weak references everywhere else in non-ARC code, e.g. delegates etc. (MRC doesn't have zeroing weak references; so these are the only kind of weak reference in MRC. Yet people were still able to write safe code in the pre-ARC days.)
Basically, the solution is that you need a clear map of ownership. Either self is responsible for keeping the block alive; or some other object is responsible for keeping the block alive.
For example, with delegates, usually, a "parent" object is the delegate of a "child" object; in this case the "parent" object is responsible for keeping the "child" object alive, so the "parent" object will outlive the "child" object, thus the back reference can be weak and is safe (because the child object's methods could only possibly be called by the parent object while the parent object is alive).
On the other hand, if you have an asynchronous operation, and the block is given to the operation as a callback, then usually the operation is responsible for holding onto the block. In this case, self would not hold onto the block. And the block would hold a strong reference to self, so that when the operation is done, it can still safely do whatever it is that it needs to do on self. In fact, whatever object self is, it doesn't even need to be retained by whoever uses it, since it is indirectly retained by the asynchronous operation -- it can just be a create, fire, and forget kind of thing.
If you have something where the block is sometimes kept alive by self, and sometimes kept alive by something else, then you should re-think your design. You say "There can be conditions when the block is executed after the self is deallocated"; well, you should describe your whole design and how this can happen. Because usually, for something that is executed asynchronously, self need not hold onto the block.
Your code is really confusing and doesn't make sense. For example, why would you assign to a parameter (myClassProperty)? What's the point of passing an argument when the parameter is going to be overwritten anyway? Why would you name a local variable "myClassProperty"?
What I think you are asking about is accessing a property that can be changed on different threads, and how to deal with the memory management of that. (This question is unrelated to blocks or ARC/MRC. It is equally an issue in ARC.)
The answer is that you need an atomic property. You can make a synchronized property atomic, or implement an atomic property manually if you know how. What an atomic property of object pointer type needs to do is its getter needs to not just return the underlying variable, but also retain and autorelease it, and return the result of that. The retrieval and retaining in the getter occurs in a critical section that is synchronized with a critical section in the setter that includes the release of the old value and retaining of the new. Basically, this synchronization guarantees that the value will not be released in the setter in between retrieving the value and retaining it in the getter. And the value returned from the getter is retained and autoreleased, so it is guaranteed to be alive for the duration of the scope.
Solution for 2)
__block MyClass *blockSelf = self;
self.myBlock = ^{
datatype* p = [blockSelf.someProperty retain];
[blockSelf someMethod:p];
[p release];
};
// I am taking someProperty in an method argument
-(void) someMethod:(datatype*)myClassProperty
{
myClassProperty = abc;
}
For 1) don't know how you use myBlock. If it's used only by self, then all will be fine. And if it's used by some other object, then it's also should have retained reference at self and then there is also all will be fine.
Right now I have something like this:
- (void)viewDidLoad
{
MyObject *myObject = nil;
#autoreleasepool
{
myObject = [[MyObject alloc] init];
[myObject doSomethingWithBlock:^{
NSLog(#"Something Happened");
}];
}
NSLog(#"End of method");
}
And the doSomethingWithBlock: has the following:
- (void)doSomethingWithBlock:(void(^)())aBlock
{
[self performSelector:#selector(something:) withObject:aBlock afterDelay:4.0f];
}
And the something:
- (void)something:(void(^)())aBlock {
aBlock();
}
I understand that the block is being passed between stacks frames, so it's kept alive until it actually is executed and it is disposed. But why when the "End of method" is called does myObjct still exists? I know that I am not referencing the object from within the block, so shouldn't it be released within the autorelease pool? Or is this a compiler detail (if it should actually release it there, or after the method returns), and I shouldn't care about it?
Someone pointed out that performSelector will retain the target so I used this instead:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 4 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
aBlock();
});
It is not clear to me whether the question is about the lifetime of the block, as per the title, or the lifetime of the object referenced by myObject, so we'll cover both.
First, the stack allocation of blocks in an optimisation and something programmers should not really need to be aware of. Unfortunately when blocks were first introduced the compiler was not smart enough to handle this optimisation completely automatically, hence the need to know about Block_copy() etc. But the compiler is now much smarter and the programmer can pretty much forget about stack allocation of blocks.
This answer applies to Xcode 5.0.2/Clang 4.2. Use a different (earlier) version and YMMV.
Second, the block:
^{ NSLog(#"Something Happened"); }
is not actually stack allocated at all. As it references no values from the environment it is statically allocated and never needs to be placed on the stack or moved to the heap - another optimisation. To get a stack allocated block just change it to:
^{ NSLog(#"Something Happened: %p", self); }
which will be stack allocated (and don't worry about possible retain cycles, that's another topic...)
With that out of the way, let's look at the lifetimes:
The object:
The variable myObject has a lifetime of at most the call to viewDidLoad, the variable is created on entry to the method and destroyed on exit, if precise lifetime semantics are in force, or earlier if not needed and precise lifetime semantics are not in force - the latter is the default allowing the compiler to optimise storage use (independent of ARC). By default local variables have a strong ownership qualifier, so an ownership interest is asserted for any reference stored in one. ARC will release that ownership interest when another reference is stored in the variable or when the variable itself is destroyed. The latter will happen in this case and the variable is destroyed at some time after the last use of it and the end of the method - depending on how the compiler does its optimisations.
All this means that the object referenced by myObject may or may not be still around at your call to NSLog(). In the case of using performSelector:withObject:afterDelay: that call will assert ownership over the object until after the selector has been executed -= so the object will live. In the case of using dispatch_after the object is not required and so will not stay alive.
The block:
As mentioned above as written the block is statically allocated so lifetime is easy - it always exists. More interesting is modifying it as above to make it stack allocated.
If the block is stack allocated it will exist in the stack frame of the viewDidLoad call and unless moved or copied to the heap it will disappear when that call returns.
The call to doSomethingWithBlock: will be passed a reference to this stack allocated block. This is possible as doSomethingWithBlock: expects a block and code within it can move it to the heap if needed as it knows it is a block.
Now it gets interesting. Within doSomethingWithBlock: in the performSelector:withObject:afterDelay: case the block is passed as the withObject: parameter which is of type id - which means the called code expects a standard Objective-C object and those live on the heap. This is a case of type information loss, the caller has a block, the callee only sees an id. So at this point the compiler inserts code to copy the block to the heap and passes that new heap block to performSelector:withObject:afterDelay: - which treats it as it would any other object. [Older compilers did not always do this, the programmer had to know that type information loss was about to occur and manually insert code to move the block to the heap.]
In the case of dispatch_after, the function argument is block typed so the compiler just passes a stack allocated block on. However the dispatch_after function copies the block to the heap, as per its documentation, and there is no problem.
So in either case a stack allocated block is copied to the heap before viewDidLoad finishes and its stack frame is destroyed taking with it the stack allocated block.
HTH.
It is declared outside of the autorelease pool, so it should exist after it. It's all about scope where the object is declared, not allocated. By your logic class variables allocated inside an autorelease pool should be nil'd at the end of the pool and not usable elsewhere.
Example
-(void)function
{
MyObject *object; //MyObject declared here
if(someBoolean)
{
object = [[MyObject alloc] init]; //MyObject allocated here
}
//This is outside the scope of allocation,
//but it's still inside the scope of declaration.
//If ARC referenced the scope of allocation your
//object would not be valid here, as ARC would
//release it as out of scope.
}
I am working through some retain-cycle issues with blocks/ARC, and I am trying to get my head around the nuances. Any guidance is appreciated.
Apple's documentation on "Blocks and Variables" (http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/bxVariables.html) says the following:
If you use a block within the implementation of a method, the rules
for memory management of object instance variables are more subtle:
If you access an instance variable by reference, self is retained; If
you access an instance variable by value, the variable is retained.
The following examples illustrate the two different situations:
dispatch_async(queue, ^{
// instanceVariable is used by reference, self is retained
doSomethingWithObject(instanceVariable);
});
id localVariable = instanceVariable;
dispatch_async(queue, ^{
// localVariable is used by value, localVariable is retained (not self)
doSomethingWithObject(localVariable);
});
I find this explanation confusing.
Is this appropriate use of the "by value" / "by reference" terminology? Assuming that these variables are of the same type (id), it seems like the distinguishing characteristic between them is their scope.
I do not see how self is being referenced in the "by reference" example? If an accessor method were being used, (e.g. - below), I could see self being retained.
doSomethingWithObject(self.instanceVariable);
Do you have any guidance on when one might want to do things one way or the other?
If conventional wisdom is to utilize the "by value" variables, it seems like this is going to result in a lot of additional code for additional variable declarations?
In a circumstance where nested blocks are coming into play, it seems like it may be more maintainable to avoid declaring the blocks inside of each other as one could ultimately end up with a potpourri of unintentionally retained objects?
Think of the case of using instanceVariable as an equivalent of writing self->instanceVariable. An instance variable is by definition "attached" to the self object and exists while the self object exists.
Using instanceVariable (or self->instanceVariable) means that you start from the address of self, and ask for an instance variable (that is offset of some bytes from the self object original address).
Using localVariable is a variable on its own, that does not rely on self and is not an address that is relative to another object.
As the blocks capture the variables when they are created, you typically prefer using instance variables when you mean "when the block is executed, I want to get the value of the instance variable at the time of the execution" as you will ask the self object for the value of the instance variable at that time (exactly the same way as you would call [self someIVarAccessorMethod]). But then be careful not to create some retain cycles.
On the other hand, if you use localVariable, the local variable (and not self) will be captured when the block is created, so even if the local variable changes after the block creation, the old value will be used inside the block.
// Imagine instanceVariable being an ivar of type NSString
// And property being a #property of type NSString too
instanceVariable = #"ivar-before";
self.property = #"prop-before";
NSString* localVariable = #"locvar-before";
// When creating the block, self will be retained both because the block uses instanceVariable and self.property
// And localVariable will be retained too as it is used directly
dispatch_block_t block = ^{
NSLog(#"instance variable = %#", instanceVariable);
NSLog(#"property = %#", self.property);
NSLog(#"local variable = %#", localVariable);
};
// Modify some values after the block creation but before execution
instanceVariable = #"ivar-after";
self.property = #"prop-after";
localVariable = #"locvar-after";
// Execute the block
block();
In that example the output will show that instanceVariable and self.property are accessed thru the self object, so self was retained but the value of instanceVariable and self.property are queried in the code of the block and they will return their value at the time of execution, respectively "ivar-after" and "prop-after". On the other hand, localVariable was retained at the time the block was created and its value was const-copied at that time, so the last NSLog will show "locvar-before".
self is retained when you use instance variables or properties or call methods on self itself in the code of the block. Local variables are retained when you use them directly in the code of the block.
Note: I suggest you watch the WWDC'11 and WWDC'12 videos that talks about the subject, they are really instructive.
Is this appropriate use of the "by value" / "by reference" terminology? It's at least analogous to the typical use. Copying a value to a local variable is like copying a value onto the stack; using an ivar is like passing a pointer to a value that's stored somewhere else.
I do not see how self is being referenced in the "by reference" example? When you use an instance variable inside a method, the reference to self is implied. Some people actually write self->foo instead of foo to access an ivar just to remind themselves that foo is an ivar. I don't recommend that, but the point is that foo and self->foo mean the same thing. If you access an ivar inside a block, self will be retained in order to ensure that the ivar is preserved for the duration of the block.
Do you have any guidance on when one might want to do things one way or the other? It's useful to think in terms of the pass by reference/pass by value distinction here. As AliSoftware explained local variables are preserved when the block is created, just as parameters passed by value are copied when a function is called. An ivar is accessed through self just as a parameter passed by reference is accessed through a pointer, so its value isn't determined until you actually use it.
it seems like this is going to result in a lot of additional code for additional variable declarations? Blocks have been a feature of the language for a while now, and I haven't noticed that this is a problem. More often, you want the opposite behavior: a variable declared locally that you can modify within a block (or several blocks). The __block storage type makes that possible.
it seems like it may be more maintainable to avoid declaring the blocks inside of each other as one could ultimately end up with a potpourri of unintentionally retained objects? There's nothing wrong with letting one or more blocks retain an object for as long as they need it -- the object will be released just as soon as the blocks that use it terminate. This fits perfectly with the usual Objective-c manual memory management philosophy, where every object worries only about balancing its own retains. A better reason to avoid several layers of nested blocks is that that sort of code may be more difficult to understand than it needs to be.