Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

multithreading - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...