gpt4 book ai didi

iphone - NSDefaultRunLoopMode 与 NSRunLoopCommonModes

转载 作者:IT王子 更新时间:2023-10-29 07:29:15 27 4
gpt4 key购买 nike

每当我尝试在 UIScrollViewMPMapView 或其他东西后面下载一个大文件时,只要我触摸 iPhone 屏幕,下载过程就会停止。值得庆幸的是,Jörn 发表了一篇很棒的博客文章建议使用 NSRunLoopCommonModes 进行连接的替代选项。

这让我详细了解了这两种模式,NSDefaultRunLoopMode 和 NSRunLoopCommonModes,但是 apple 文档没有友好地解释,只是说

NSDefaultRunLoopMode

The mode to deal with input sources other than NSConnection objects. This is the most commonly used run-loop mode.

NSRunLoopCommonModes

Objects added to a run loop using this value as the mode are monitored by all run loop modes that have been declared as a member of the set of “common" modes; see the description of CFRunLoopAddCommonMode for details.

CFRunLoopAddCommonMode

Sources, timers, and observers get registered to one or more run loop modes and only run when the run loop is running in one of those modes. Common modes are a set of run loop modes for which you can define a set of sources, timers, and observers that are shared by these modes. Instead of registering a source, for example, to each specific run loop mode, you can register it once to the run loop’s common pseudo-mode and it will be automatically registered in each run loop mode in the common mode set. Likewise, when a mode is added to the set of common modes, any sources, timers, or observers already registered to the common pseudo-mode are added to the newly added common mode.

谁能用人类语言解释一下这两者?

最佳答案

运行循环是一种允许系统唤醒休眠线程以便它们可以管理异步事件的机制。通常,当您运行一个线程(主线程除外)时,可以选择是否在运行循环中启动线程。如果线程在不与外部事件交互且没有计时器的情况下运行某种排序或长时间运行的操作,则不需要运行循环,但如果您的线程需要响应传入事件,则应将其附加到运行循环以便当新事件到达时唤醒线程。 NSURLConnection 生成的线程就是这种情况,因为它们只在传入事件(来自网络)上唤醒。

每个线程都可以关联到多个运行循环,或者可以关联到一个特定的运行循环,该运行循环可以设置为在不同模式下工作。 “运行循环模式”是操作系统用来建立一些规则的约定,用于确定何时传递某些事件或收集它们以便稍后传递。

通常所有运行循环都设置为“默认模式”,它建立了管理输入事件的默认方式。例如:一旦发生鼠标拖动(Mac OS)或触摸(在 iOS 上)事件,则此运行循环的模式将设置为事件跟踪;这意味着线程不会被新的网络事件唤醒,但是当用户输入事件终止并且运行循环再次设置为默认模式时,这些事件将在稍后传递;显然,这是操作系统架构师做出的选择,以优先考虑用户事件而不是背景事件。

如果您决定通过使用 scheduleInRunLoop:forModes: 更改您的 NSURLConnection 线程的运行循环模式,那么您可以将线程分配给一个特殊的运行循环 < em>mode,而不是特定的默认运行循环。称为 NSRunLoopCommonModes 的特殊伪模式被许多输入源使用,包括事件跟踪。例如,将 NSURLConnection 的实例分配给普通模式意味着除了“默认模式”之外,还将其事件关联到“跟踪模式”。将线程与 NSRunLoopCommonModes 关联的优点/缺点之一是线程不会被触摸事件阻塞。

新模式可以添加到普通模式中,但这是一个相当低级的操作。

我想通过添加一些注释来结束:

  • 通常我们需要使用一组图像或从网络下载的带有表格 View 的缩略图。我们可能认为在表格 View 打开时从网络下载这些图像滚动可以改善用户体验(因为我们可以同时看到图像滚动),但这不是有利的,因为滚动会受到很大影响。在这个带有 NSURLConnection 的示例中,不应使用运行循环;最好使用 UIScrollView 委托(delegate)方法来检测滚动何时终止,然后更新表格并下载新项目来自网络;

  • 您可以考虑使用 GCD,这将帮助您“屏蔽”您的代码来自运行循环管理问题。在上面的示例中,您可以考虑将您的网络请求添加到自定义串行队列。

关于iphone - NSDefaultRunLoopMode 与 NSRunLoopCommonModes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7222449/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com