Kenneth
Kenneth

Reputation: 677

iphone - stopping a method that is running?

i have a [self parseXMLFileAtURL:path] method. is there anyway of stopping it midway? like terminating the method.

Reason for doing is because im running an apache http server on one pc and if the server is not running, the app will 'hang' if this method is called. so i want to to something like terminating the method after a certain amount of seconds , 5s maybe. and display an alert message.

Upvotes: 3

Views: 497

Answers (3)

Steve
Steve

Reputation: 31642

I'd have two suggestions... one, if you possibly can, use NSMutableURLRequest with NSURLConnection to retrieve the data; which gives you much better control over things like timeout.

NSError * error;
NSURLResponse * response;

NSMutableURLRequest * request = [NSMutableURLRequest
     requestWithURL:[NSURL URLWithString:@"http://..."]
     cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
     timeoutInterval:60.0];

// Not sure if you need this, but I frequently do POSTs as well, so whatever:
[request setHTTPMethod:@"GET"];

NSData * responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSString * xml = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];

(NB: You'll have to check the error response, I just omitted it for clarity)

Also, ideally (since in my example I use the synchronous method) this should be run on a background thread... but I found it much easier to run this on the background thread manually using "performSelectorInBackground:" and use the synchronous methods, than I did using the async methods. Keep in mind, you'll have to create your own auto release pool if you do that... but that's two lines, and it's super easy.

Short of that, it IS possible to terminate the method... you'd have to run it on a different thread, and kill the thread if it took too long... but really, the NSMutableURLRequest isn't so bad, and it already gives you the timeout options you're looking for.

The thread programming guide at: http://developer.apple.com/iphone/library/documentation/cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html#//apple_ref/doc/uid/10000057i-CH15-SW2 talks about killing threads... and tells you (indirectly) how to do it... but if you simply kill the thread, you are almost guaranteed to leak something.

Upvotes: 5

zneak
zneak

Reputation: 138031

I'm pretty sure that you could try installing a signal handler with sigaction to handle SIGALRM and use the alarm function. There is, however, probably a better solution using the Cocoa framework. I'll leave this here, but it's probably not the easiest way.

Upvotes: 2

John Smith
John Smith

Reputation: 12797

A method is just a C(++) function, so there really no way to stop it.

Upvotes: 0

Related Questions