What is the recommended pattern for the following GCD / blocks scenario? - objective-c

I have a question about Grand Central Dispatch, blocks and memory management. Consider this code:
Worker *myWorker = [[Worker alloc] init];
[work doAsyncStuffWithBlock:^(NSMutableDictionary *info)
{
NSLog(#"processing info results");
}];
[myWorker release];
Here, I want the doAsyncStuffWithBlock to happen asynchronously and then perform the block when it has some results. Meanwhile this main code will continue on. Is it safe here to release myWorker? Will the dispatch_queue I implement internally keep a reference of it around to eventually execute that block? Or, should I release it inside the block? that seems weird. Thanks for any suggestions.

When a block references an Objective-C object, e.g.:
Worker *myWorker = [[Worker alloc] init];
[work doAsyncStuffWithBlock:^(NSMutableDictionary *info)
{
NSLog(#"processing info results");
[myWorker doSomething];
}];
[myWorker release];
it automatically retains that object and, when the block is released, it automatically releases that object.
So yes, you should release myWorker in your code, and no, you shouldn’t release myWorker inside the block.

Read
this
or this
You can release outside the block.

Related

Do I need to release my singleton object?

I have a singleton object in my app:
+ (id)shared {
#synchronized(self) {
if (sharedDownloadFirstData == nil)
sharedDownloadFirstData = [[self alloc] init];
}
return sharedDownloadFirstData;
}
- (id) init {
if (self = [super init]) {
}
return self;
}
And I want to know if I need to realese it (I am not using ARC). To do that I am using:
[[DownloadFirstData shared] release];
Did I need to release this object? I have an array and other stuff in the object that I need to release.
In Objective-C, you should only ever call release on an object you own. This typically means an object you've created with alloc, init, copy or mutableCopy or otherwise called retain on. Here, the consumer of [DownloadFirstData shared] didn't call any of those functions and is not responsible for releasing it. You will see this any time you call [UIColor blackColor], for instance.
You may want to call retain on such an object, if you are crossing autorelease boundaries or are just not sure of the lifetime:
DownloadFirstData *local = [[DownloadFirstData shared] retain];
...
[local release];
In this case, you've taken ownership and are responsible for releasing.
But what about the definition of shared? When you define a method not using init..., you are typically responsible for leaving with a release count of 0, with something like [[self alloc] init] autorelease]. This is not the case for the singleton because your goal is for it to always exist and therefore always have a non-zero retain count. You make this happen simply by not releasing it after you create it.
there is no sense in having a singleton if you will release it.
Usually a singleton is created because you want the same object till the app ends.
At the end of your app life cycle all memory related to the app is freed.
Use a standard approach, if you need alloc release often.
if your singleton takes a lot of memory, you should consider to write it better.
anyway, [[DownloadFirstData shared] release]; will work.

Why do I need to 'block copy' when I want to use the block?

ProductCenterController __weak *tempSelf = self;
void(^block)(void) = ^{
tempSelf.actIndView = ....
[tempSelf.view addSubview:tempSelf.actIndView];
};
[NSThread detachNewThreadSelector:#selector(actionForThreadBlock:) toTarget:self withObject:block];
I find Leak - '_Block_copy_internal'...(I use ARC)
and then when I change the last line code to something like this ,the leak missing...:
[NSThread detachNewThreadSelector:#selector(actionForThreadBlock:) toTarget:self withObject:[block copy]];
if I dont use [block copy], why it will cause a leak????
I think ,the block will release after the function and the thread will release all after finished...
how it will cause a leak?
Blocks are created on the stack, so they are released when your method (scope) ends. Some time after your thread will try to execute the already deallocated block, ending in exception.
Copy moves the block from stack to heap memory, so it will live even after the original method ends.
Please refer to Apple documentation when the subject is discussed extensively.

Objective-C: Using a block as a completion handler

I'm using CLGeocoder, and I'm using a block as a completion handler. I'm unsure of the retain/release cycle for the instance of CLGeocoder that I create.
Here's the basic code:
CLGeocoder* geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:
^(NSArray* placemarks, NSError* error)
{
// process the placemarks...
[geocoder autorelease];
}
];
Is autoreleasing the geocoder as the last line of the block the recommended way to handle this? Any suggestions are appreciated!
You can just release it (no need for auto release) Auto release is for when you are unsure when you will need to release an object (such as returning an object at the end of a method or for convenience methods)
In this case you are certain that you are done using the object so it may be released. Of course, autorelease works too, but lingers around in memory longer.

Multithreading and autorelease pool

As I'm mastering my skills with multithreading with GCD, I've come across some question. Suppose you have the following method:
- (void)method {
NSString *string= [NSString string]; //will be autoreleased
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//very very lengthy operation...
NSLog(#"%#", string); //is it safe?
});
}
I'm wondering if this is correct, because I think I should have retained string before the block execution: in fact I fear that the event loop finishes and sends string an autorelease message before using string in the block. That would crash the program.
Am I right? Should I send a retain and a release message to string or this is the correct implementation?
Thanks in advance!
I'm wondering if this is correct, because I think I should have retained string before the block execution: in fact I fear that the event loop finishes and sends string an autorelease message before using string in the block.
Fear not:
A block captures the scope of the surrounding method/function in that it automatically retains any object-variable that is used inside of the block. Be aware of that when you use self inside of a block, as this may greatly affect the lifetime of the object!
There is one exception to this rule, and that are variables declared as
__block SomeObjectPointerType variableName
Update
Because there’s a new comment on this answer, I should probably add that things changed a little with the introduction of ARC:
Under ARC all object variables default to __strong, and this holds for variables marked with __block as well. If you want to avoid strong capturing of a variable in a block, you should define a local variable that is __weak.
End Update
If you like to learn more about blocks, bbum gave an excellent session called Introducing Blocks and Grand Central Dispatch on iPhone at WWDC 2010.
The "Block Details" section starts at 11:30.
The concern is; when an autorelease object releases?
NSString *myString= [NSString stringWithFormat: #"%#", stringVariable];
The myString depends upon stringVariable, whenever stringVariable releases the myString immediately releases.
NSString *myString= [NSString stringWithString: #"stringVariable"];
In practice it is observed the myString might be releases just after the completion of the method.
Now if you change your code and use NSAutoReleasePool
- (void)method {
NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init];
NSString *string= [NSString string]; //will be autoreleased
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//very very lengthy operation...
// string will be released here
[pool release];
NSLog(#"%#", string); // it is not safe?
});
}
The autorelease objects released when the auto release pool releases in which they exists or when the object releases on which they depends.
Now if you are using the method in a thread you should use auto release pool inside it.
- (void)method {
NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init];
// lengthy operations ...
[pool release];
}

ObjC delegate methods never gets called

I am creating instances of a class FlickrImage parsing a Flickr API photos response. The class has a method getLocation that does another API call to get the geolocation:
NSLog(#"getting location for %i",self.ID);
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
OFFlickrAPIRequest *flickrAPIRequest = [[OFFlickrAPIRequest alloc] initWithAPIContext[appDelegate sharedDelegate].flickrAPIContext];
[flickrAPIRequest setDelegate:self];
NSString *flickrAPIMethodToCall = #"flickr.photos.geo.getLocation";
NSDictionary *requestArguments = [[NSDictionary alloc] initWithObjectsAndKeys:FLICKR_API_KEY,#"api_key",self.ID,#"photo_id",nil];
[flickrAPIRequest callAPIMethodWithGET:flickrAPIMethodToCall arguments:requestArguments];
[pool release];
I have implemented the callback method that would catch the response from the API and update the FlickrImage instance with the geolocation data - but it never gets called. Here's where the instances get created:
NSDictionary *photosDictionary = [inResponseDictionary valueForKeyPath:#"photos.photo"];
NSDictionary *photoDictionary;
FlickrImage *flickrImage;
for (photoDictionary in photosDictionary) {
flickrImage = [[FlickrImage alloc] init];
flickrImage.thumbnailURL = [[appDelegate sharedDelegate].flickrAPIContext photoSourceURLFromDictionary:photoDictionary size:OFFlickrThumbnailSize];
flickrImage.hasLocation = TRUE; // TODO this is actually to be determined...
flickrImage.ID = [NSString stringWithFormat:#"%#",[photoDictionary valueForKeyPath:#"id"]];
flickrImage.owner = [photoDictionary valueForKeyPath:#"owner"];
flickrImage.title = [photoDictionary valueForKeyPath:#"title"];
[self.flickrImages addObject:[flickrImage retain]];
[flickrImage release];
[photoDictionary release];
}
The retain is there because I thought it might help solve this but it doesn't - and doesn't the NSMutableArray (flickrImages is a NSMutableArray) retain its members anyway?
EDIT I should add that the getLocation method (first code snippet) is launched in a thread:
[NSThread detachNewThreadSelector:#selector(getLocation) toTarget:self withObject:nil];
Your delegate method is never being called because the request is never being made. When you call callAPIMethodWithGET:, it sets up communications to run asynchronously on the current thread's run loop, then returns immediately. That way you can safely call it on the main thread without blocking.
Because you are calling the method from a thread you created yourself, it does not see the main run loop, but the run loop for your new thread. However, because you never execute the run loop, the messages are never sent, a response is never received, and your delegate is never called.
You could fix this by calling [[NSRunLoop currentRunLoop] run] in your new thread. That will let the work happen. But in this case would be easier to never detach a new thread in the first place. Your program won't block, and you won't have to worry about your delegate method needing to be reentrant.
I've also run into this problem when requesting and parsing XML on a different thread my solution was to do this:
while([[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:start] && !isFinished){
}
Where start = [NSDate dateWithTimeIntervalSinceNow:3]; this is basically a timeout so that it doesn't live forever and isFinished is set to true when my parsing has completed.
I'm not familiar with these flicker API wrappers, but in this code:
NSDictionary *requestArguments = [[NSDictionary alloc] initWithObjectsAndKeys:FLICKR_API_KEY,#"api_key",self.ID,#"photo_id",nil];
Are you certain that both FLICKR_API_KEY, and self.ID are not nil? If either of them is nil, you'll end up with a dictionary that has less items in it than you intend.
Could you post the callback method(s) you have implemented – this could be just down to a simple typo, as it appears OFFlickrAPIRequest won’t do anything if the delegate does not implement the required callback.
Did you also implement flickrAPIRequest:didFailWithError: to see if there was an error returned from the API call?
Okay, I did solve it, with help from some of the suggestions above.
I did remove the extra retain because it did in fact create a memory leak. It did not look right from the outset, so my gut feeling about that is worth something, which is a good thing ;)
I removed the redundant threading because the API call is already asynchronous and does not require an additional thread to be non-blocking. After that, the callback method was being called but I ran into different problems concerning object retention. If interested you might want to check out that question, too
Thanks all.
The setDelegate method of OFFlickrAPIRequest does not retain the delegate like it should. This means you're stuck ensuring that your delegate is alive as long as the request is (or patching the class to properly own its own references).