码迷,mamicode.com
首页 > 其他好文 > 详细

objectc delegate 代理的用途

时间:2014-11-28 17:59:43      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:http   io   ar   os   使用   sp   for   strong   on   

我简单的总结了一下自己用到的委托的作用有两个,一个是传值,一个是传事件。
1.所谓传值经常用在b类要把自己的一个数据或者对象传给a类,让a类去展示或者处理。(切分紧耦合,和代码分块的时候经常用)
2.所谓传事件就是a类发生了什么事,把这件事告诉关注自己的人,也就是委托的对象,由委托的对象去考虑发生这个事件后应该做出什么反映。(这个经常见,例如在异步请求中,界面事件触发数据层改变等等)
3.利用委托赋值,这种方法感觉是为了不暴露自己的属性就可以给自己复值,而且这样更方便了类的管理,只有在你想要让别人给你赋值的时候才调用,这样的赋值更可控一些。(例如tableView中的委托(dateSource)中常见)。
 
最后,我想分享一下在使用委托的时候的一些心得和注意事项。
 
心得:delegate的命名要准确,尽量看名字就知道用法。delegate和通知有的用法有些象,但是前者是单对单的,后者是单对多的情况。
注意:在dealloc要把delegate至为nil,还有就是delegate设置属性的时候要用assign,不要用retain。

 

stack overflow的解释

http://stackoverflow.com/questions/2534094/what-is-a-delegate-in-objective-cs-iphone-development

 

A delegate allows one object to send messages to another object when an event happens. For example, if you‘re downloading data from a web site asynchronously using theNSURLConnection class. NSURLConnection has three common delegates:

 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

One or more of these delegates will get called when NSURLConnection encounters a failure, finishes successfully, or received a response from the web site, respectively.

 

A delegate is a pointer to an object with a set of methods the delegate-holder knows how to call. In other words, it‘sa mechanism to enable specific callbacks from a later-created object.

good example is UIAlertView. You create a UIAlertView object to show a short message box to users, possibly giving them a choice with two buttons like "OK" and "Cancel". TheUIAlertView needs a way to call you back, but it has no information of which object to call back and what method to call.

To solve this problem, you can send your self pointer to UIAlertView as a delegate object, and in exchange you agree (by declaring theUIAlertViewDelegate in your object‘s header file) to implement some methods thatUIAlertView can call, such asalertView:clickedButtonAtIndex:.

 

The delegate fires the automatic events in Objects C. If you set the delegate to Object, it sends the message to another object through the delegate methods.

It‘s a way to modify the behavior of a class without requiring subclassing.

Each Objects having the delegate methods.These delegate methods fires, when the particular Objects take part in user interaction and Program flow cycle.

Simply stated: delegation is a way of allowing objects to interact with each other without creating strong interdependencies between them.

objectc delegate 代理的用途

标签:http   io   ar   os   使用   sp   for   strong   on   

原文地址:http://www.cnblogs.com/shupaopao/p/4128981.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!