首页 \ 问答 \ 捕获Swift中的闭包值(Capturing closure values in Swift)

捕获Swift中的闭包值(Capturing closure values in Swift)

我的问题与其他几个人非常相似,但我无法实现。 我正在通过我编写的帮助程序类进行API调用。

首先,我尝试了一个带有返回值的标准函数,结果与预期一致。 我厌倦分配结果后完成后台任务。

现在我正在使用闭包,并且可以将值返回到视图控制器中,但它仍然停留在闭包中,我也遇到了同样的问题。 我知道我需要使用GCD来将任务发生在主队列中。

这是我在视图控制器中所拥有的

var artists = [String]()
let api = APIController()
    api.getArtistList("foo fighters") { (thelist) -> Void in
        if let names = thelist {
            dispatch_async(dispatch_get_main_queue()) {
                artists = names
                print("in the closure: \(artists)")
            }
        }
    }

    print ("method 1 results: \(artists)")

结果是:

method 1 results: []
in the closure: [Foo Fighters & Brian May, UK Foo Fighters, John Fogerty with Foo Fighters, Foo Fighters, Foo Fighters feat. Norah Jones, Foo Fighters feat. Brian May, Foo Fighters vs. Beastie Boys]

我知道为什么会发生这种情况,我只是不知道如何解决这个问题:( API调用需要是异步的,那么捕获这些结果的最佳做法是什么?根据用户在表视图中选择的内容,我将进行后续的api调用,因此它不像我可以处理闭包内的所有内容


My question is very similar to several others here but I just can't get it to work. I'm making an API call via a helper class that I wrote.

First I tried a standard function with a return value and the result was as expected. The background task completed after I tired to assign the result.

Now I'm using a closure and I can get the value back into my view controller but its still stuck in the closure, I have the same problem. I know I need to use GCD to get the assignment to happen in the main queue.

this is what I have in my view controller

var artists = [String]()
let api = APIController()
    api.getArtistList("foo fighters") { (thelist) -> Void in
        if let names = thelist {
            dispatch_async(dispatch_get_main_queue()) {
                artists = names
                print("in the closure: \(artists)")
            }
        }
    }

    print ("method 1 results: \(artists)")

as the results are:

method 1 results: []
in the closure: [Foo Fighters & Brian May, UK Foo Fighters, John Fogerty with Foo Fighters, Foo Fighters, Foo Fighters feat. Norah Jones, Foo Fighters feat. Brian May, Foo Fighters vs. Beastie Boys]

I know why this is happening, I just don't know how to fix it :( The API calls need to be async, so what is the best practice for capturing these results? Based on what the user selects in the table view I'll be making subsequent api calls so its not like I can handle everything inside the closure


原文:https://stackoverflow.com/questions/31279369
更新时间:2022-03-20 13:03

最满意答案

这基本上归结为一个关于并发性的问题( http://docs.mongodb.org/manual/faq/concurrency/ )能够在创建写入密集型负载时,在单个数据库级别编写器贪婪锁定上执行读取。

MongoDB应该能够在这里很好地兼顾你的读锁定,交织操作并在它认为适合保持性能提升的某些条件下产生当前操作(参见上面提供的链接)。

当然,这与读取和写入操作被隔离的SQL形成对比,因此这意味着MongoDBs并发规则实际上打破了ACID中的I。 当然,在SQL中,锁更精细,因此您可以正常获得相对性能。

如果你确实看到性能受到影响,主要是由于IO(读取需要IO也记得),那么你可能会发现谨慎地将你的写入批量分组为1000个,每批后大约需要5秒钟才能让IO消退。


This essentially comes down to a question about concurrency ( http://docs.mongodb.org/manual/faq/concurrency/ ) being able to do reads on a single database level writer greedy lock performantly while creating a write intensive load.

MongoDB should be able to juggle your read lock with the write lock quite well here, interweaving operations and yielding the current operation under certain conditions that it sees fit to keep performance up (see link supplied above).

This is, of course, in contrast to SQL where read and write operations are isolated, as such this means that MongoDBs concurrency rules actually break the I in ACID. Of course, in SQL the lock is much more granular so you would get relative performance normally.

If you do see a performance hit, mainly due to IO (reading requires IO as well remember) then you might find it prudent to batch your writes into groups of maybe 1000, taking about a 5 second break after each batch to let the IO subside.

相关问答

更多
  • 简而言之,我可以管理: 在关系数据库引擎中,所有操作(无论是否在存储过程中)通常会使用基于集合的逻辑*更好地扩展,因为这些引擎已针对基于集合的操作进行了优化。 对于引擎中的单个原子操作,通常有固定的资源成本(可能相当高),无论它是否影响1或1,000,000行。 游标会导致更高的成本,因为数据库引擎必须将游标的状态保持在原子操作成本之上。 *在过程逻辑比基于集合的执行更好的地方,会出现一些边缘案例/类问题(具体取决于您的RDBMS)。 As succinctly as I can manage: In re ...
  • 不确定是否有更好的方法,但一个选项可能是将具有相同条件的列组合在一起并使用行上的all来减少使用的&操作数量: mask = (df[['Fare_amount', 'Total_amount']] >= 2.5).all(1) & \ (df[['Tip_amount', 'Tolls_amount', 'Extra']] >= 0).all(1) & \ (df.Trip_distance > 0) & \ (df.Passenger_count.between ...
  • 我之前的项目实际上是在MVC中进行计费系统。 我清楚地记得测试如果我使用Task然后快速退出网站会发生什么。 它完成了所有计算,在SQL Server中运行了一个存储过程,并在完成后向我发送了一封电子邮件。 所以,回答你的问题:如果你将操作包装在一个Task它应该完成,没有任何问题。 My previous project was actually doing a billing system in MVC. I distinctly remember testing out what would happ ...
  • 我使用SET Operation而不是Trigger解决了这个问题 INSERT Into [dbo].[LogAudit] (GuidId, Query, Params, TableName, CreatedDate, Operation, UserId) SELECT '00000000-0000-0000-0000-000000000000', 'INSERT INTO Table(col6, col5, col4, col3, col2, ...
  • 显然,SSIS在内部使用游标来处理你需要的一些任务 - 对于MS开发人员来说,使用游标是很常见的。 您可以尝试通过运行项目并禁用任务并运行它或者非常仔细地阅读进度选项卡来隔离错误输出的任务。 我会尝试,对于执行SQL任务,将旁路准备转为true并再次尝试任务。 It turns out that the environment was patched in such a way where the database indices needed rebuilt. As a result of that, t ...
  • 我通常会把它作为3号从演示者告诉视图向用户展示“长时间运行”的操作反馈......无论对视图意味着什么(等待光标,消息等) I usually do it as no.3 from the presenter tell the view to show the user a "long running operation" feedback... whatever that means for the view (wait cursor, message, etc.)
  • 可以通过乘以倒数,然后进行一些微调来执行除以常数(并且只有65536个)的除法。 由于此方法对于有限范围是准确的,因此可以使用某些技术将64位操作数减少到更小的值(仍然与原始值一致): // pseudo code -- not c a = 0x1234567890abcdefULL; a = 0x1234 << 48 + 0x5678 << 32 + 0x90ab << 16 + 0xcdef; a % N === ((0x1234 * (2^48 % N) + // === means 'is ...
  • 这基本上归结为一个关于并发性的问题( http://docs.mongodb.org/manual/faq/concurrency/ )能够在创建写入密集型负载时,在单个数据库级别编写器贪婪锁定上执行读取。 MongoDB应该能够在这里很好地兼顾你的读锁定,交织操作并在它认为适合保持性能提升的某些条件下产生当前操作(参见上面提供的链接)。 当然,这与读取和写入操作被隔离的SQL形成对比,因此这意味着MongoDBs并发规则实际上打破了ACID中的I。 当然,在SQL中,锁更精细,因此您可以正常获得相对性能。 ...
  • 你可以使用MERGE ;WITH Source AS ( SELECT field1, MIN(COALESCE(field2, -2)) as field2 FROM MyTable tempfact LEFT JOIN MyTable sd ON tempfact.ID = sd.ID AND sd.TransactionId = @transactionId WHERE tempfact.SomeField IS NULL ...
  • ObjectId的生成在本地发生,它不是数据库操作。 4个值用于生成ObjectId: 时间::Time.new.to_i 机器ID: Digest::MD5.digest(Socket.gethostname).unpack("N")[0] 进程ID: Process.pid % 0xFFFF 计数器: @counter = (@counter + 1) % 0xFFFFFF 你可以在这里找到完整的代码。 Generation of the ObjectId happens locally, it's n ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。