简体   繁体   中英

How do I transfer data between threads in iOS?

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

Please correct me if I am wrong, but my understanding is that NSPipe from Cocoa is only used for the transfer of data between processes but not between threads. In addition, since it makes use of some local directory for this, I would assume that some temporary file is used for such transfers. To summarize,

  1. Assuming that Operation Queues are used, what class can I use in Cocoa to transfer binary data from one thread to another without writing my own synchronization and without making use of temporary files?
  2. If there isn't any, what would be an elegant alternative?

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 were definitely not created for that purpose. Objective-C threads are built on POSIX, but they all share the same virtual memory space, so you typically will not do any IPC in ObjC either.

If your looking to 'share' data between threads in Objective C, just write it to an appropriate variable, and if necessary, send a signal between the threads that the data is available to be used. The best way to do this is via the use of Conditions.

If you are going to do any non-trivial threading work in Obj C then I highly recommend you read Apple's guide on thread safety .

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

performSelector:onThread:withObject:waitUntilDone:modes

Assume 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]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM