How to handle NSZombies in an asynchronous NSURLConnection? - iphone

I'm currently asynchronously using NSURLConnection with several UIViews (every view handles NSURLConnection as delegate). The problem I have is when user switches views too fast and the delegate becomes NSZombie the app crashes - that is NSURLConnection doesn't have living delegate anymore. So, the first question is if there's a way to circumvent this?
The second question is simple - how do I handle NSZombie? Simple if(myObject != nil).. doesn't work at all.

You need to cancel the NSURLConnection before you dispose it's delegate. Simply keep a reference to the NSURLConnection in your UIView that acts as a delegate and call [urlConnection cancel].
After you release a message you need to set your pointer to it to nil if you continue using that pointer. As an example:
id myObject = [[SomeObject alloc] init];
/* Some code */
[myObject release];
myObject = nil;
/* Some more code */
if (myObject != nil) {
[myObject doSomething];
}
Notice however that it is valid to send a message to nil so you don't need to safe guard the message sending. It simply won't have any effect if myObject == nil.

Related

Passing data between classes / asynchronous requests / iOS

I am converting my application from Syncronous to Asyncronous HTTP requests and have ran into a problem that looks like it will require quite a big reworking of how the application handles its data. Let me try to explain
Previously it was like this:
-Class1, Class2 and Class3 were all subclasses of UIViewController
-Helper class
-Content display class
They do broadly different things but the common trait is their interaction with the helper class. They gather details of a request in a number of different ways from a user and then eventually send a request to the helper class.
When it was done syncronously the helper class would return the data. Each class would then interpret the data (XML files) and pass them on to the Content display class via a segue
So something broadly like this:
Class1:
//Get user input
SomeData *data = [helperclass makerequest];
id vcData = [data process];
[self performSegueWithIdentifier:#"segueIdentifier"];
---
- (void)prepareForSegue:(UIStoryboardSegue *)segue
{
DestinationViewController *destination = (DestinationViewController *)segue.destinationViewController;
destination.data = vcData;
}
Content display class:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.data presentdata];
}
Now it looks like this
I dealt with this problem by first making it work with Class1 with a view to deploying the fix to class2 and class3. So class1 and helper now interact like this
Class1:
//Get user input
SomeData *data = [helperclass makerequestWithSender:self];
id vcData = [data process];
[self performSegueWithIdentifier:#"segueIdentifier"];
---
- (void)prepareForSegue:(UIStoryboardSegue *)segue
{
DestinationViewController *destination = (DestinationViewController *)segue.destinationViewController;
destination.data = vcData;
}
Now the biggest problem I am facing is how to get the data from helperclass back to Class1. I managed to get it to work by doing
(void)makeRequestWithSender:(Class1*)sender
{
[NSURLConnection sendAsynchronousRequest:...
{
[sender sendData:data];
}
}
However, when I have came to roll this out to the other 2 GUI classed which will compose the request I am having difficulty with. My first thought was to set sender:(id) but that fails at the line [sender sendData:data] telling me that id does not have an method sendData: or similar.
Hopefully I wasn't too vague here and you guys can help. If required I will be able to post code snippets but for now can anyone help with a better suggestion about how to structure the code for this request?
You basically want to use the 'observer pattern' or a (maybe) slightly changed setup, so you can use delegation.
Observer pattern
You gain the mechanic via the NSNotificationCenter and NSNotifications. Your 3 different UIViewController subclasses each subscribe to a specific NSNotification and you notify them via posting a notification via the NSNotificationCenter.
The following code is an example of how you can approach the problem in your viewcontroller subclasses:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// subscribe to a specific notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(doSomethingWithTheData:) name:#"MyDataChangedNotification" object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
// do not forget to unsubscribe the observer, or you may experience crashes towards a deallocated observer
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
...
- (void)doSomethingWithTheData:(NSNotification *)notification {
// you grab your data our of the notifications userinfo
MyDataObject *myChangedData = [[notification userInfo] objectForKey:#"myChangedDataKey"];
...
}
In your helper class, after the data changed you have to inform the observers, e.g.
-(void)myDataDidChangeHere {
MyDataObject *myChangedData = ...;
// you can add you data to the notification (to later access it in your viewcontrollers)
[[NSNotificationCenter defaultCenter] postNotificationName:#"MyDataChangedNotification" object:nil userInfo:#{#"myChangedDataKey" : myChangedData}];
}
via #protocol
Presuming all your UIViewController subclasses reside in a parent viewcontroller, you can implement a protocol in your helper class and make the parent viewcontroller the delegate. Then the parent viewcontroller may inform the child uiviewcontrollers via passing a message.
Your helper class declaration could look like this (presuming ARC):
#protocol HelperDelegate;
#interface Helper : NSObject
#property (nonatomic, weak) id<HelperDelegate> delegate;
...
#end
#protocol HelperDelegate <NSObject>
-(void)helper:(Helper *)helper dataDidChange:(MyDataObject*)data;
#end
In the helper implementation you would inform the delegate via:
...
if ([self.delegate respondsToSelector:#selector(helper:dataDidChange:)]) {
[self.delegate helper:self dataDidChange:myChangedDataObject];
}
...
Your parent viewcontroller would need to be the delegate of the helper class and implement its protocol; a rough sketch, in the declaration
#interface ParentViewController : UIViewController <HelperDelegate>
and for the implementation in short version
// you alloc init your helper and assign the delegate to self, also of course implement the delegate method
-(void)helper:(Helper *)helper dataDidChange:(MyDataObject*)data {
[self.myCustomChildViewController doSomethingWithTheNewData:data];
}
Besides..
You might ask yourself which method to prefer. Both are viable, the main difference is that via the observer pattern you get more objects to be informed 'at once', whereas a protocol can only have one delegate and that one has to forward the message if needed. There are a lot of discussions around about pros and cons. I'd suggest you read up on them once you made up your mind (sorry ain't got enough reputation to post more than two links, so please search on stackoverflow). If something is unclear, please ask.
Some reasonable ideas here. To elaborate/add my opinion:
First, which object ought to tell the downloader (HelperClass) to begin downloading? My practice is to do this in the view controller that will present the data. So I generally start network requests after a segue (like in viewWillAppear: of the presented vc), not before.
Next, when one class needs to execute code provided for another, I first think about if it makes sense to do it using a block. Very often (not always) blocks make more sense and provide more readable code than, say, delegate, notification, KVO, etc. I think NSURLConnection completion, for example, is better suited to blocks than delegate. (and Apple kind of agrees, having introduced + (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler).
So my pattern for your app would be this:
// Class1.m
// when user has completed providing input
...
// don't do any request yet. just start a segue
[self performSegueWithIdentifier:#"ToContentDisplayClass" sender:self];
...
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// don't do a request yet, just marshall the data needed for the request
// and send it to the vc who actually cares about the request/result
if ([segue.identifier isEqualToString:#"ToContentDisplayClass"]) {
NSArray *userInput = // collect user input in a collection or custom object
ContentDisplayClass *vc = segue.destinationViewController;
vc.dataNeededForRequest = userInput;
}
...
Then in ContentDisplayClass.m
// this is the class that will present the result, let it make the request
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
HelperClass *helper = [[HelperClass alloc]
initWithDataNeededForRequest:self.dataNeededForRequest];
// helper class forms a request using the data provided from the original vc,
// then...
[helper sendRequestWithCompletion:^(NSURLResponse *response, NSData *data, NSError *error) {
if (!error) {
// interpret data, update view
self.label.text = // string we pulled out of data
} else {
// present an AlertView? dismiss this vc?
}
}];
This depends on HelperClass implementing the block form of NSURLConnection
// HelperClass.m
- (id)initWithDataNeededForRequest:(id)dataNeededForRequest {
// standard init pattern, set properties from the param
}
- (void)sendRequestWithCompletion:(void (^)(NSURLResponse *, NSData *, NSError *))completion {
NSURLRequest *request = ...
// the stuff we need to formulate the request has been setup in init
// use NSURLConnection block method
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:completion];
}
Edit - there are several rationale's for making the VC transition before starting the network request:
1) Build the standard behavior around the success case: unless the app is about testing network connections, the success case is that the request works.
2) The cardinal principal for an app is to be responsive, to do something sensible immediately upon user actions. So when the user does something to initiate the request, an immediate vc transition is good. (what instead? a spinner?). The newly presented UI might even reduce the perceived latency of the request by giving user something new to look at while it runs.
3) What should an app do when a request fails? If the app doesn't really need the request to be useful, then doing nothing is a good option, so you'd want to be on the new vc. More typically, the request is necessary to proceed. The UI should be "responsive" to request failure, too. Typical behavior is to present an alert that offers some form of "retry" or "cancel". For either choice, the place the UI wants to be is on the new vc. Retry is more obvious, because that's where it always is when it tries to fetch the data. For cancel, the way to be "responsive" to cancel is to go back to the old vc, a vc transition back isn't ugly, it's what the user just asked for.
I'm not 100% clear on how you're handling the data now, but to change your data to asynchronous calls, I would use blocks. For instance your current synchronous code like this:
//Get user input
data = [helperclass makerequest]
sendData = [data process]
would turn into something like this:
//Get user input
data = [helperclass makerequestWithSuccess:^{
sendData = [data process]
}];
Using a success block will allow you to wait to process the data until the makerequest was finished.
Your new makerequest function would now look like this:
-(void)makerequestWithSuccess:(void (^)(void))success{
// Put your makerequest code here
// After your makerequest is completed successfully, call:
success();
}
Hope this helps!
I'm not sure that I understood your problem correctly, but if it's sort of:
Start task A asynchronously.
When task A finished successfully, get its result and start task B whose input is result A.
When task B finished successfully, get its result and start task C whose input is result B.
...
When finished successfully, be happy, otherwise print error.
A code example would look like this:
typedef (void)(^completion_block_t)(id result);
-(void) asyncTaskA:(completion_block_t)completionHandler;
-(void) asyncTaskBWithInput:(id)input completion:(completion_block_t)completionHandler;
-(void) asyncTaskCWithInput:(id)input completion:(completion_block_t)completionHandler;
-(void) asyncSomethingWithCompletion:(completion_block_t)completionHandler;
-(void) asyncSomethingWithCompletion:(completion_block_t)completionHandler
{
[self asyncTaskA:^(id resultA){
if (![resultA isKindOfClass:[NSError class]]) {
[self asyncTaskBWithInput:resultA completion:^(id resultB){
if (![resultB isKindOfClass:[NSError class]]) {
[self asyncTaskCWithInput:resultB completion:^(id resultC) {
completionHandler(resultC);
}];
}
else {
completionHandler(resultB); // error;
}
}];
}
else {
completionHandler(resultA); // error
}
}];
}
And you use it like:
[self asyncSomethingWithCompletion:^(id result){
if ([result isKindOfClass:[NSError class]]) {
NSLog(#"ERROR: %#", error);
}
else {
// success!
self.myData = result;
}
}];
The "continuation" and error handling makes this a bit confusing (and Objective-C syntax doesn't really add for more readability).
Another example with a third party library support:
The same logic can be written as this:
-(Promise*) asyncTaskA;
-(Promise*) asyncTaskBWithInput;
-(Promise*) asyncTaskCWithInput;
-(Promise*) asyncSomething;
- (Promise*) asyncSomething
{
return [self asyncTaskA]
.then(id^(id result) {
return [self asyncTaskBWithInput:result];
}, nil)
.then(id^(id result) {
return [self asyncTaskCWithInput:result];
}, nil);
}
And it is used as follows:
[self asyncSomething]
.then(^(id result) {
self.myData = result;
return nil;
},
^id(NSError* error) {
NSLog(#"ERROR: %#", error);
return nil;
});
If you like the latter more, the "Promise" framework is available on GitHub: RXPromise - I'm the author ;)
I'm not sure if what I've done in the past is relevant to your problem, but what I've done is create a download class that has a delegate protocol with a single method: -(void)downloadFinished:(id) data.
Any class that needs to get asynchronous data, creates an instance of this download class, and sets itself as the delegate. I call downloadFinished: from both connection:didFailWithError: and connectionDidFinishLoading:. Then, in the implementation of that method in the delegate, I check whether the data's class is NSData or NSError, and evaluate that data however is appropriate for that class.

block delegate methods of class in iphone

I am having a problem I am working on a class which is subclass of UITextField.
Which will be used in many classes further.
But I don't want to let user to use it's delegate methods in any way.
Is there any way to do this ?
Override setDelegate: so that it throws an exception or logs an instruction on what to do. That way your API users will know what's actually going on.
-(void) setDelegate: (id <UITextFieldDelegate>) delegate
{
NSLog(#"*** Use the blocks API instead of calling %s", __PRETTY_FUNCTION__);
[self doesNotRecognizeSelector: _cmd];
}
Override the -setDelegate: method such that it never actually sets a delegate. You can just provide an empty method that fails to call super:
-(void) setDelegate:(id<UITextFieldDelegate>) delegate
{
// this method intentionally empty to prevent a delegate from ever being set
}

Delegate callback from other NSThread

I have object with .delegate property which i manipulate in method 'doJob'. I assign this property with 'self' and my function is being called when this object finishes his job. Till now everything is fine.
Now i want to manipulate this object in a separate thread.
I'm using [NSThread detachNewThreadSelector...] to run the 'doJob' function.
In this case my delegate method not being called. I guess this is because 'self' points to new thread instead of main one. Ok. I'm passing self as argument to function while creating the thread and it still not working. What do i miss?
my current code is as follows:
- (void)mainFunction
{
[NSThread detachNewThreadSelector:#selector(doJob:) toTarget:self witObject:self];
}
- (void)doJob:(MyObject*)parentThread
{
ManipulatedObject *obj = [[ManipulatedObject alloc] init];
obj.delegate = parentThread;
[object startJob];
}
GCD will make most of your multi-threading troubles trivial. You can do something like this:
- (void)mainFunction
{
// Runs your task on a background thread with default priority.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
ManipulatedObject * obj = [[ManipulatedObject alloc] init];
[obj startJob]; // I'm assuming this is sychronous.
// The callback is explicitly run on the main thread.
dispatch_async(dispatch_get_main_queue(), ^{
// Your callback here.
[obj release];
});
});
}
That's all you have to do, it's that simple. All the relevant code is inline and together.
If you want the ManipulatedObject to explicitly invoke the block, then you could add that ability to ManipulatedObject. To do so, you should:
Define the block type for convenience typedef void(^MyCallback)();
Add #property (nonatomic, copy) MyCallback block; and #synthesize block. Don't forget the copy.
Invoke the block when you need to dispatch_async(dispatch_get_main_queue(), [self block]);.
If your delegate needs to make more than one kind of callback, then you will need a block for each callback. It's a minor inconvenience, but it's worth it for all the conveniences you gain.
For a more thorough explanation of blocks and GCD, check out WWDC 2011 session 308.
Well firstly you do not need to pass self as the witObject: parameter, (which is spelt wrong) because - (void)doJob:(MyObject*)parentThread is still in the same object (self is the same in both threads), self has nothing to do with your main thread its MyObject presumable, you also have a problem were you are not creating a new autorelease pool for your doJob:, doJob: should look like
- (void)doJob:(MyObject*)parentThread
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
ManipulatedObject *obj = [[ManipulatedObject alloc] init];
obj.delegate = parentThread;
[object startJob];
[pool release];
}
you have to give us some information about how you're delegate method is being called, if it is tying to use timers or something like that then you are going to have problems because there is no runloop to add your timer to.

Objective-C equivalent of Java's BlockingQueue?

I'm just getting into iPhone development after many years doing Java development. I'm looking for the Objective-C equivalent to Java's BlockingQueue. Is there something like that?
In case I'm going about things the wrong way, here's what I'm trying to achieve:
I want to display, one at a time, chunks of data pulled from a network server. To keep the user from noticing network lag, I want to always have a few chunks of data pre-fetched. In Java-land, I'd use a thread-safe queue between my fetching thread and my display thread.
Here's an implementation of a blocking queue with a queue and dequeue method. The expectation would be that one thread goes into a loop calling dequeueUnitOfWorkWaitingUntilDate: and processes units of work while a second thread is calling queueUnitOfWork:.
#interface MyBlockingQueue : NSObject {
NSMutableArray *queue;
NSConditionLock *queueLock;
}
- (id)dequeueUnitOfWorkWaitingUntilDate:(NSDate *)timeoutData;
- (void)queueUnitOfWork:(id)unitOfWork;
#end
enum {
kNoWorkQueued = 0,
kWorkQueued = 1
}
#implementation MyBlockingQueue
- (id)init {
if ((self = [super init])) {
queueLock = [[NSConditionLock alloc] initWithCondition:kNoWorkQueued];
workItems = [[NSMutableArray alloc] init];
}
return self;
}
- (void)dealloc {
[queueLock release];
[workItems release];
[super dealloc];
}
- (id)dequeueUnitOfWorkWaitingUntilDate:(NSDate *)timeoutDate {
id unitOfWork = nil;
if ([queueLock lockWhenCondition:kWorkQueued beforeDate:timeoutDate]) {
unitOfWork = [[[queue objectAtIndex:0] retain] autorelease];
[queue removeObjectAtIndex:0];
[queueLock unlockWithCondition:([workItems count] ? kWorkQueued : kNoWorkQueued)];
}
return unitOfWork;
}
- (void)queueUnitOfWork:(id)unitOfWork {
[queueLock lock];
[queue addObject:unitOfWork];
[queueLock unlockWithCondition:kWorkQueued];
}
#end
You can simply spin off an NSOperation and post a notification when the data has come back (finished loading). Take a look at Dave Dribin's blog post on concurrency with NSOperation that shows how to encapsulate an NSURLConnection session:
http://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations/
If you are not talking about accessing a web service or site where NSURLConnection is appropriate, you can instead use Cocoa Async Socket if it's straight TCP/IP or UDP:
http://code.google.com/p/cocoaasyncsocket/
Best Regards,
I don't think such a thing exists natively - you're probably going to have to write your own class that maintains a queue of network objects. Your header might look something like:
#interface ObjcBlockingQueue : NSObject {
// The objects that you're holding onto
NSArray *objects;
}
#property(nonatomic,retain) NSArray *objects;
- (ServerData *)getNextChunk;
Then you can implement getNextChunk to pop and return the top object off your objects array, and if [objects count] is less than a certain value, launch a thread to fetch some more objects (probably using NSURLConnection with ObjcBlockingQueue being the delegate). You can also have that thread/connection launched inside an overridden init method to prefill the queue.
You might also want to think about adding a
- (BOOL)isChunkAvailable;
method that will let your display thread know whether it can display something new right away or if it has to display a loading message. Depending on where you're displaying the data and how your app is structured, it may also be worth your while to make ObjcBlockingQueue a singleton class.

Why should I write [anView release], anView = nil; rather than [anView release];?

Somewhere I was reading that - regarding low memory warnings and giving up an non-visible view with all it's subviews (= a whole nib, I think), you should do that:
-(void)dealloc {
[anView release], anView = nil;
[someImageView release], someImageView = nil;
[super dealloc];
}
rather than
-(void)dealloc {
[anView release];
[someImageView release];
[super dealloc];
}
What's the reason for grounding those pointers to nil (= "no object"), after I call release? Let me guess: Some other method could have -retain'ed the view for some reason (anyone any example for when this could happen?), then the didReceiveMemoryWarning thing happens, and you release a whole nib+view that's currently not visible (i.e. in a multiview-app). As soon as the user wants to see that view again, you would quickly load the nib again and then: It loads all views, connects the outlets, and BANG! Your other retain'ed view's are hanging now without any pointer somewhere lonely in the memory brick, causing a fat and deep memory leak until your app crashes.
Right/Wrong?
The principle is more general than UIView. indeed it is more general than Objective-C/Cocoa -release method. It is valid also with C malloc()/free() memory functions.
When you no longer need an object or any memory zone, first you release/free it. Then, to make sure that you won't use it again, you clear the means to access this object or memory zone by assigning a nil to an object or a NULL to a memory pointer.
Some other method could have -retain'ed the view for some reason
Unless you're invoking dealloc yourself, it's only called when the retain count becomes zero.
Note that in Objective-C sending a message to a nil "object" is (often) perfectly fine. Doing so will not make your program halt, but the message is simply ignored. However, you cannot send a message to a freed object, which would yield a crash.
So, the following would give you an error:
[anView release];
[anView doSomething];
But, this is in fact ok:
[anView release];
anView = nil;
[anView doSomething];
It's a matter of taste, but for the above, you might in fact prefer to crash your program, rather than wondering why doSomething is not executed...
See also Sending Messages to nil from Apple's Introduction to The Objective-C 2.0 Programming Language.
The -dealloc method is called when the object is freed and no other methods on the object will be executed after. Therefore, setting any instance variable to nil has no effect outside that object.
If you were releasing an object (without using a setter) somewhere else in the class, it would be important to set the instance variable to nil to prevent code elsewhere from sending a message to that address.
I use this pattern a lot:
- (void) showHelp: (id) sender
{
if (helpController == nil)
{
helpController = [[HelpController alloc] initWithNibName: #"Help" bundle: [NSBundle mainBundle]];
}
[self presentModalViewController: helpController animated: YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
[helpController release];
helpController = nil;
}
Pretty much everywhere that I allocate a viewcontroller that is modal, or otherwise "temporary". This way, it hangs around if I need it again, but goes away if memory gets low.
rather than doing the expicit release and set to nil, if your accessors have properties associated with them yoc and do the following as a more concise method:
- (void) dealloc
{
self.retainedProperty1 = nil;
self.retainedProperty2 = nil;
self.copiedProperty = nil;
self.assignedProperty = nil;
}
this way you can have code that has less repetition since the synthesized code will take care of your releases for you.
Edit: i should point out that your properties can't be readonly or else you get compiler errors for obvious reasons :)