iOS设计:在库中使用委托模式 [英] iOS Design: Using the delegate pattern in a library
问题描述
如果我的iPhone控制器代码响应触摸事件,则调用库进行URL请求,如何我最好以异步方式执行请求?
在库中,如果我使用ASIHTTPRequest示例代码中所示的异步请求的委托模式,如何从库回到iPhone控制器中的调用代码?
如果我改为使用库内的ASIHTTPRequest进行同步URL请求,那么将调用放到库中最简单的方法是什么从iPhone控制器在一个单独的线程,以避免绑定UI线程?
对于任何人的未来参考,最简单的方法发现是使用ASIHTTPRequest中内置的异步请求功能,将我的库对象设置为委托,并将didFinishSelector:和didFailSelector:值设置为不同的会话hods在我的图书馆内的每个请求。
在处理每个响应结束时,我将解析的响应(NSString *或NSArray *)分配给我的库对象的属性,而不是返回一个值。 / p>
当我的iOS视图控制器委托被加载时,我使用键值观察。当响应被解析并分配给库中的属性时,observeValueForKeyPath:ofObject:change:context:method在我的视图控制器委托的代码中被调用,从那里我可以知道哪个属性被改变,因此什么UI需要更新。
I have a library project that uses ASIHTTPRequest to make URL requests and parse the responses. The library will be used by a separate iPhone app project.
If my iPhone controller code responds to a touch event, then calls into the library to make URL requests, how do I best perform the requests asynchronously?
In the library, if I use the delegate pattern for asynchronous requests as shown in the ASIHTTPRequest sample code, how do I return data from the library back to the calling code in the iPhone controller?
If I instead make synchronous URL requests with ASIHTTPRequest inside the library, what's the easiest way to put the calls to the library from the iPhone controller on a separate thread to avoid tying up the UI thread?
For anyone's future reference, the easiest approach I found is to use the async request functionality built into ASIHTTPRequest, setting my library object as the delegate and setting the didFinishSelector: and didFailSelector: values to different methods inside my library for each request.
At the end of processing each response, I assign the parsed response (an NSString* or NSArray*) to a property of my library object instead of returning a value.
When my iOS view controller delegate is loaded, I add a change observer to each of the properties in the library using Key-Value Observing. When the response is parsed and assigned to the property in the library, the observeValueForKeyPath:ofObject:change:context: method is called in the code of my view controller delegate, and from there I can figure out which property was changed and therefore what UI needs to be updated.
这篇关于iOS设计:在库中使用委托模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!