views:

73

answers:

2

Hello,

In an iPad app I'm developing, I need to put the network handling on a separate thread since it occasionally blocks the UI of the app. At the moment, I have created a Connection object in which all the networking logic goes (NSStreams and its delegate methods).

The main obstacle is how to create the secondary thread and schedule the NSStreams on the run loop of this thread. Do I explicitly create an NSThread that is then owned by the Connection object?

I have been experimenting with NSOperation, but this didn't seem like the best solution as I feel the need for a thread dedicated to handling networking events.

Pointers and advice are welcome. Any sample code might be helpful as well.

Bart

A: 

I did just some googling, and I came up with this:

http://kdl.nobugware.com/post/2008/12/22/nsthread-iphone-template/

I think this is what you need ;)

EDIT: http://www.xprogress.com/post-36-threading-tutorial-using-nsthread-in-iphone-sdk-objective-c/ Maybe that is usefull to...

If you read the code, you see performSelectorOnMainThread (or something) so you can send back info from thread to thread.

dododedodonl
+1  A: 

I like the detachNewThreadSelector... approach too, but FYI you can use NSOperation and NSOperationQueue. It'll throw non-concurrent operations onto separate threads.

To get the streams going, you're looking at this kind of thing:

[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:mode];

Definitely look at the Apple sample "PictureSharing" at http://developer.apple.com/library/mac/#samplecode/PictureSharing.

In particular, copy the FileSendOperation and FileReceiveOperation classes, and the QRunLoopOperation. I also use the LinkedImageFetcher sample's QWatchedOperationQueue class, which works well with the PictureSharing classes. I took their *SendOperation and *ReceiveOperation classes and turned them into classes sending/receiving what I needed (some NSData).

Then it's as easy as:

 FileSendOperation *op;
 op = [[[FileSendOperation alloc] initWithFilePath:somePath outputStream:outStream ] autorelease];

 [self.queue addOperation:op finishedAction:@selector(networkingDone:)];
Graham Perks