Objective C: Memory management in Block cases - objective-c

I am wondering if I am using blocks as shown in the code below
__block Loader *loader = [[Loader alloc]initWithResourcePath:self.resourcePath];
[loader setCompletionHandler:^(NSArray *anArray){
self.answerArray=anArray;
[self reloadData];
}];
[loader getObjects];
My question is with regards to memory management. The analyzer tells me that there is a potential leak (since I did an alloc/init for my loader). How can I stop the leak here? I tried to release the loader at the end but that causes my app to stop functioning. Any advise is appreciated here

Several issues:
there is no reason for loader to be declared __block; you aren't re-assigning in the block and, thus, the __block is pointless.
the leak is because you alloc/init the loader, but never release it
do not name methods getSomething; the get prefix is reserved for methods that return stuff by reference. Just call it objects. If it is supposed to trigger the load, then call it load or performLoad.
If it is asynchronous, then getObjects is pointless. If synchronous, then the completion block is pointless.
If loader is to be used synchronously, release it at the end of the method. If it is asynchronous, then the completion block could release it. Note that the use of __block in this case is still pointless; while referring to loader in the completion block will create a retain cycle, it will be broken when you explicitly Block_release() the block in your loader (because you must have done a Block_copy() when setting the completion handler if it is to be used asynchronously in the first place).

If you plan to use loader outside of the function calling your block, it is highly possible that you need to store it in a ivar of your controller (I guess, it is a controller, but I don't know what kind of class owns the code you shows). Once you do that, you can release it in your dealloc.
The reasoning is that loader should live across several methods and runloop cycles, so a local variable will not do.
Otherwise, just release it at the end of the block, once you have done with it.
If this does not seem right to you, then possibly more code is needed.

I'm going to make some assumptions: 1) The completion handler (block) is used by method getObjects. 2) getObjects is asynchronous (it returns to the caller right away though it continues to process).
With these assumptions you can't send release after sending getObjects because getObjects is still using the completion handler.
Try sending a release or autorelease at the end of the completion handler. That should free loader provided reloadData is not also asynchronous.

Related

In Objective-c is performSelector executed inline or is it posted for execution as a different event?

There are plenty of reasons why this matters. Here's a simple example if you weren't using ARC.
[instance performSelector:selector withObject:objectA];
[objectA release]; // Did the selector actually finish executing
// in the line above so everyone's done with objectA
// or did the selector merely get scheduled in the line
// above, and is yet to execute, so objectA had better
// not be released yet?
I've done some research and context clues seem to point to selector getting done inline. But I haven't seen any definitive statement anywhere I've looked, that states it gets executed inline.
performSelector:withObject: is executed synchronously (block until the method finished).
Use performSelector:withObject:afterDelay: to execute method asynchronously on main thread (return immediately and execute later).
Use performSelectorInBackground:withObject: to execute method asynchronously on background thread (return immediately and execute on different thread).
Note:
performSelector and its friends should be avoid because it is undefined behaviour if you use them on method with incompatible method signature.
The aSelector argument should identify a method that takes no arguments. For methods that return anything other than an object, use NSInvocation.
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/index.html#//apple_ref/occ/intfm/NSObject/performSelector:
Did the selector actually finish executing in the line above so
everyone's done with objectA or did the selector merely get scheduled
in the line above, and is yet to execute, so objectA had better not be
released yet?
It doesn't matter, for memory management purposes. Memory management in Cocoa is local -- you only need to care what your function does; you don't need to know, and shouldn't care, what other functions do internally, to manage memory correctly (ignoring retain cycles). As long as you're done with your owning reference, you should release it. It doesn't matter to you if other people are done with it.
This is because, according to Cocoa memory management rules, any function which needs to store it for use beyond the function call is required to retain it and release it when it's done (because the function cannot assume that the object lives beyond the calling scope otherwise). Any function which uses an argument asynchronously (e.g. performSelector:withObject:afterDelay: etc.) does indeed retain the object and release it when it's done.
Alternately, think about it this way: How does ARC work? How does ARC know whether a function uses its argument synchronously or asynchronously? It doesn't. There is no annotation that tells the compiler whether a function uses something synchronously or asynchronously. Yet ARC does it correctly. That means you can too, without knowing whether the function uses its argument synchronously or asynchronously.

When do I release this block?

I was looking at some code in this thread How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?. I was wondering, if the block does something asynchronously, when should the block be released?
Let's say I have code that looks like this:
- (void)testMethod:(id)parameter
{
dispatch_block_t block = ^{
SomeAsyncTask *t = [SomeAsyncTask withCompletionBlock:^{
[parameter doAction];
}];
};
[self performSelector:#selector(executeBlock:)
onThread:backgroundThread
withObject:block
waitUntilDone:NO];
dispatch_release(block); //I can release the block here because performSelector retains the block
}
- (void)executeBlock:(id)block
{
block();
}
Is the key then, that the completion block in SomeASyncTask will retain the parameter so it's safe to release the block?
Ken Thomases's answer is correct. I want to give a more detailed response to your comments.
First, it is not clear whether you meant performSelector:withObject: or performSelector:withObject:afterDelay:, since performSelector:withObject: is a direct synchronous call, so [self performSelector:#selector(runBlock:) withObject:block_]; is identical to [self runBlock:block_]. I'll assume it's performSelector:withObject:afterDelay:, since performSelector:withObject: is less interesting.
Look at it step by step. performSelector:withObject:afterDelay: retains its argument, so you can release it after giving the block to it. And performSelector:... retains it through the performance of its selector. So during the runBlock, the block is valid because it is still retained by performSelector:.... During the execution of the block, it is still valid (since it is still inside the execution of runBlock). doSomethingAsynchronouslyWithCompletionBlock must retain its argument if it is asynchronous. And so on.
But you don't need to look at it that way. Once you think through it, you will realize that the memory management rules are made so that you don't need to worry about what other code does, only what you need locally.
The memory management rules boil down to the following conditions: Every function / method expects its arguments to be valid when it is called (which usually means through the duration of the function call, since the calling function does not run during this time, so how can it become invalid, unless this function does something which indirectly removes it (like removing from a dictionary)?); and does not have any expectations about how long it will remain valid after the function call. That's it. Everything follows from this.
For example, in your doWork, you only care about how long you need to use the block. Since you don't need it after performSelector:..., you can safely release it. It doesn't matter that performSelector:... might do something with it asynchronously; you may not even know that it is asynchronous (e.g. you could be choosing an unknown method to call dynamically). The point is, what it does doesn't matter. Why? Because the performSelector:... does not assume the argument to be valid any longer than when you called it. So if it needs to keep it longer (and it does), it must retain it (but you don't need to know this). And it will retain it for as long as it needs it.
Similarly, runBlock can assume that the argument it was given is valid for the duration of its call. Since it does not need to keep it around for longer (all it does is call the block), it does not need to retain it. The block does not change this. Why? Again, because the block does not assume its arguments (including the block itself) is valid after its call, so runBlock doesn't need to guarantee it. If the block calls doSomethingAsynchronouslyWithCompletionBlock, that's fine. doSomethingAsynchronouslyWithCompletionBlock does not assume anything is valid beyond its call, so if it is truly asynchronous, it must retain it somewhere. etc.
You can release it immediately after invoking -performSelector:withObject:afterDelay:. (I assume you meant to use the after-delay variant.) As usual, you are responsible for your memory management and other code is responsible for its memory management. Which is another way of saying that -performSelector:withObject:afterDelay: has to retain the receiver and the object that's passed in until after the selector has been performed.
Edited to add: By the way, why wouldn't you use dispatch_after() as illustrated in the answer to the question to which you linked?
I might just try passing an array with the arguments.

Method with blocks inside NSOperation - how does it work?

I'm working on an iOS project that has to work from iOS4. I have an NSOperationQueue and I add an operation. The main method of the operation looks something like this:
-(void)main
{
[self.client getStuffSuccess:^(Stuff *s) {
//Do something on success
} failure:^(NSError *error) {
//Do something on failure
}
}
The code inside the block will only be called when getStuff calls success or failure. I thought that in the meanwhile, my operation would be removed from the NSOperationQueue and the block wouldn't be called. However, I tested it and the block was in fact called. It's called no matter if the client calls the success block on the dispatch_get_main_queue or on the thread that called it - in this case the operation above.
Before the block is called, the method isFinished is actually returning true (I overrode the isFinished method and checked the value), so can someone explain me how is it possible that the block is being called?
I'm asking all this because although this works fine for one call, when I add it in a cycle of a few hundred iterations, I get an EXC_BAD_ACCESS and understanding the above might help me on the debugging.
The code inside the block will only be called when getStuff calls success or failure. I thought that in the meanwhile, my operation would be removed from the NSOperationQueue and the block wouldn't be called.
What leads you to believe this. A block is a closure, a self-contained block of code. It does not rely on the existence of some other object (the NSOperation in this case) in order to exist. You might want it to rely on that other object, but that's up to you to enforce. Ideally, I'd make getStufSuccess:failure: synchronous. If you can't you can use an NSCondition or call NSRunLoop methods to block the thread cheaply until it's done.
You also need to consider thread safety here. Your problem might not have to do with the operation going away, but your block doing something that isn't thread-safe.
Since getStuffSuccess:failure is asynchronous, you need to use a concurrent operation. Here is a helpful blog post:
http://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations/
If your -getStuffSuccess:failure doesn't block the thread (i.e. the method is asynchronous), then your -main will complete and your operationQueue may deallocate your operation before the success or failure blocks are called. You can block the thread by adding a:
while(notProcessed){
sleep(0.1);
//Make sure your success and failure functions update notProcessed BOOL
}
so that main never completes before you've had a chance to call the closures. Or just use a synchronous method. This is generally fine because you won't be on the UI thread anyways.

Calling a block from within an inner block

I have a Cocoa/Objective-C class with a method that looks something like this:
- (void)doWork:(void (^)(void))handler
{
[self->someObject doActualWork:kWorkID handler:^(Result *result) {
if (handler)
handler();
}];
}
However, when the inner block is called handler have been dealloced and the program crashes when it is called. From what I understand this is because the block is stored on the stack and thus removed soon after doWork: finishes. I'm using ARC. What should I do to fix this?
First, self-> for iVar access is an odd, and discouraged, pattern, generally.
Did you copy the blocks prior to storing 'em away for use later? If this is intended to be asynchronous code, then your actualWork:handler: method should be copying the block prior to enqueueing it.
Even under ARC; while ARC handles the return of blocks from methods automatically, it can't handle blocks as arguments automatically and you do still need to copy 'em.
If this is purely synchronous code, then something else is going wrong. You'll need to provide more clues.

after self released

I'm using a third-party Objective-C library that makes a web request in a background thread, then returns the result by using [self performSelectorOnMainThread:...] which then calls a delegate method. I understand that I need to nil the delegate reference before releasing the delegate, but I was wondering what happens if this requesting object itself gets deallocated while the background thread is running. Will this internal self reference get set to nil so that the -performSelectorOnMainThread: call is harmless, or is there a potential for a crash here?
As far as I understand your scenario (but possibly you should include some code), the statement:
[self performSelectorOnMainThread:...]
should be the last one to be executed in your thread (since it is the way to return the result of your thread, it is still part of the thread selector passed to NSThread).
If it is reasonably so, then consider that when you first detach an NSThread, you pass it a target object (your self) and the NSThread will retain it as long as the passed selector hasn't completed. This will include your [self performSelectorOnMainThread:...], so, unless someone messes heavily with releases, there should be no chance for self to be deallocated before [self performSelectorOnMainThread:...] is executed.
If your question was exactly what happens if someone messes with releases, I will give this a second thought.
If your object is deallocated before the method on the main thread completes, you have a memory management problem. The performSelectorOnMainThread:… family of methods cause the receiver to be retained until it has done its work, so the only way it could be deallocated is if you're over-releasing the object.