How to transfer data between threads in iOS?

In Java, the thread safe classes PipedInputStream and PipedOutputStream can be used to transfer data from one stream to another stream. What is its equivalent in iOS?

Please correct me if I am mistaken, but I understand that Cocoa NSPipe used only for data transfer between processes, but not between flows. In addition, since some local directory is used for this, I would suggest that some temporary file is used for such transfers. Summarizing,

  • Assuming operating queues are used, what class can I use in Cocoa to transfer binary data from one stream to another without recording my own synchronization and not using temporary files?
  • If not, then what a nifty alternative?
+7
source share
2 answers

Unlike POSIX threads created with fork, Java threads are lightweight and share the same address space. There is no need for C-Style IPC in Java, and PipedInputStream / PipedOutputStream is definitely not created for this purpose. Objective-C streams are built on POSIX, but they all use the same virtual memory space, so you will usually not make IPC in ObjC.

If you want to share data between threads in Objective-C, simply write them to the appropriate variable and, if necessary, send a signal between the threads that are available for use. The best way to do this is to use the Terms.

If you intend to do any non-trivial work with streams in Obj C, I highly recommend that you read the Apple thread safety guide .

+4
source

The easiest way to transfer data between threads is to use NSData objects along with performSelector: onThread: withObject.

execute Selector: onThread: withObject: waitUntilDone: modes

Suppose you have two threads, threadX and threadY, each with one object, objectX and objectY. Do something like:

 char buffer[100] = "Hello"; NSData *data = [NSData dataWithBytes:byBuffer length:100]; [objectY performSelector:@selector(haveSomeData:) onThread:threadY withObject:data waitUntilDone:NO modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]]; 
+1
source

All Articles