Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Are methods called by delegates and observers executed on the main thread?

Sorry, I'm not sure of the right language here, but when methods are called because they are either delegate methods, or methods called as a result of being listed as the target of an observer, are they executed on the main thread?

I'm wondering if I can just make UI changes in these methods, or do I have to wrap them in

    dispatch_async(dispatch_get_main_queue(), ^{ UI stuff });

TIA: John

like image 786
John Avatar asked Oct 24 '11 19:10

John


People also ask

What is a delegate in IOS development?

Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object. A delegate allows one object to send messages to another object when an event happens.

Why are delegates not called Swift?

This might be because you are setting the delegate and opening an another instance of the viewController which was not assigned the delegate value.

How do you call a delegate method in Objective C?

Steps in Creating a DelegateStep 1 − First, create a single view application. Step 3 − Then select Objective C Class and click Next. Step 4 − Give a name to the class, say, SampleProtocol with subclass as NSObject as shown below. Step 5 − Then select create.

What is delegate in xcode?

A delegate is an object that acts on behalf of, or in coordination with, another object when that object encounters an event in a program.


1 Answers

For delegates this can vary. If the documentation does not specify, then usually they are sent on the main thread. Traditionally UIKit must be used on the main thread so those delegates will almost always be called from the main thread.

For notifications I think you want this little snip.

A notification center delivers notifications to observers synchronously. In other words, the postNotification: methods do not return until all observers have received and processed the notification. To send notifications asynchronously use NSNotificationQueue. In a multithreaded application, notifications are always delivered in the thread in which the notification was posted, which may not be the same thread in which an observer registered itself.

From http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsnotificationcenter_Class/Reference/Reference.html

And finally for KVO, the notifications can come in from other threads. Here is what an Apple Engineer had to say about handling them.

http://lists.apple.com/archives/cocoa-dev/2007/May/msg00022.html

like image 90
logancautrell Avatar answered Oct 04 '22 02:10

logancautrell