cocoa设计模式经典摘录1

 

id

 

    The id type tells the compiler that a variable points to an object but doesn’t give the compiler any more specific information about the kind of object,hence the object is anonymous.

    Use the Anonymous Type pattern to send messages to anonymous objects,including objects that are not available at the time the sending code is compiled. Reduce coupling between classes by limiting the information that each class has about other classes. 

 

 

NSApplication,Events,and the Run Loop


    Most graphical user interface toolkits,including the Application Kit,use an event-driven model.That simply means applications react to events that are sent to the application by the operating system. Some events originate from user keyboard or mouse input.Timer events may arrive at periodic intervals. Other input sources like network sockets or inter- thread message queues may produce events.

    Cocoa applications receive events from the operating system with the help of the NSApplication and NSRunLoop classes. Every graphical Cocoa application contains one instance of the NSApplication class. NSApplication is a singleton,as described in Chapter 13,“Singleton.” The NSApplication instance creates an instance of NSRunLoop to receive events from the operating system. Multithreaded Cocoa application may use up to one NSRunLoop instance per thread.

    Run loops monitor input sources that are part of the operating system and block if no input is available.That just means that when there is no input available,the run loop doesn’t consume CPU resources. Many other user interface toolkits make the run loop a key focus for developers,but in Cocoa,the run loop plays only a small but crucial role. When input data becomes available,the run loop translates the data into events and sends Objective-C messages to various objects to process the events.

    In most cases,Cocoa programmers don’t need to access run loops directly because NSApplication takes care of all the details.The Application Kit uses the Hierarchies pat- tern and the Responder Chain pattern described in Chapters 16,“Hierarchies,” and 18,“Responder Chain,” respectively. NSApplication uses the hierarchy of objects within your application and the resulting Responder Chain to determine which objects should receive which messages in response to events.

    The NSApplication class is seldom subclassed. Instead,the behavior of an application can be modified through the use of an application delegate and notifications. Notification and Delegation are powerful patterns described in Chapters 14,“Notifications,”and 15,“Delegates,” respectively.

 

 

Delayed Perform


    To send a message after a delay,use NSObject’s - (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay method.The message with the specified selector and argument is scheduled and sent sometime after the specified delay measured in seconds.

    Delayed Perform is actually implemented by Cocoa’sNSRunLoopclass.NSRunLoopis re- sponsible for accepting user input and monitoring a Cocoa application’s communication with the underlying operating system. Requests to send delayed messages are queued with the run loop associated with the thread making the request. Each time the run loop checks for user input,it also checks for queued requests. If enough time has elapsed since a queued request was made,the run loop sends the requested message with the specified ar- gument.The run loop may not get a chance to run because the application is busy doing something else.Therefore,the run loop can’t guarantee that the requested message will be sent at a precise time. It can only guarantee that it won’t be sent too soon. If a zero delay is specified when requesting the delayed message,the message is sent as soon as possible the next time the run loop runs. In all cases, performSelector:withObject:afterDelay: returns before the requested message is sent.

    The NSObject class method,+ (void)cancelPreviousPerformRequestsWithTarget: (id)aTarget selector:(SEL)aSelector object:(id)anArgument,can be used to cancel a previously requested delayed message.This will cancel all delayed messages matching the target,selector,and argument specified and queued by the run loop for the thread canceling the request.

    The NSRunLoop class can operate in several different modes.The modes determine which sources of input are read by the run loop.The performSelector:withObject: afterDelay: method schedules requests in the NSDefaultRunLoopMode,so if the run loop isn’t in that mode,the requested message won’t be sent.To specify which run loop modes are used to queue the delayed message request,use NSObject’s - (void)performSelector: (SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray *)modes method.

 

 

 

Objective-C runtime


    The Objective-C language uses a small,fast library of functions and data structures called a runtime.Many programming languages use a runtime;Java’sVirtual Machine is one of the best known runtimes,but C++ and even C also have runtimes. Objective-C’s run- time is primarily written in standard C and can be used from C or C++ programs even if those programs aren’t compiled with an Objective-C or Objective-C++ compiler.The Objective-C runtime provides supporting technology used to implement all of Cocoa’s design patterns,but some of the patterns in this book are little more than specific applica- tions of language runtime features:

    The runtime enables dynamic loading of Objective-C objects making the Bundles pattern possible.

    The runtime creates all object instances and underlies the Dynamic Creation pattern. n The runtime directly implements   

    The Category pattern to add methods to existing classes.

    The runtime implements the messaging that is key to the Perform Selector and Delayed Perform patterns and the Proxies and Forwarding patterns.

 

 

 

Delegate


    A delegate is an object that’s given an opportunity to react to changes in another object or influence the behavior of another object.The basic idea is that two objects coordinate to solve a problem. One object is very general and intended for reuse in a wide variety of situations. It stores a reference to another object,its delegate,and sends messages to the delegate at critical times.The messages may just inform the delegate that something has happened,giving the delegate an opportunity to do extra processing,or the messages may ask the delegate for critical information that will control what happens.The delegate is typically a unique custom object within the Controller subsystem of your application.

Delegates are one of the simplest and most flexible patterns in Cocoa and are made possible by the use of the Anonymous Type pattern described in Chapter 7,“Anonymous Type and Heterogenous Containers.” Delegates highlight key advantages of using anony- mous objects when designing reusable classes.

    Delegates simplify the customization of object behavior while minimizing coupling be- tween objects. Cocoa’s NSWindow class uses a delegate to control window behavior. NSWindow is a very general class that encapsulates all aspects of windows in a graphical user interface.Windows can be resized and moved.They have embedded controls for closing,minimizing,or maximizing the window. Almost all graphical Cocoa applications use windows,yet window handling must be customized in many cases. For example,an application may need to constrain the size of a window or give users a chance to save changes to the content of a window before the window closes.

    One way to customize the behavior of the standard NSWindow class is to subclass it and implement new behaviors in the subclass. However,subclassing requires very tight cou- pling between the subclass and its superclass. Overuse of subclassing results in the creation of many classes that are application-specific and not very reusable. Subclassing statically establishes the relationship between the subclass and its superclass at compile time. In many cases,runtime flexibility is desired. For example,constraints on the resizing behav- ior of a window might change based on user actions at runtime. More importantly,the logic used to customize window behavior may depend on details of the application’s implementation. In the Model View Controller pattern emphasized throughout Cocoa,windows are clearly part of the view subsystem,but application details are better encapsu- lated within the model or controller subsystems. Subclassing NSWindow to add application logic causes a contamination between the separate subsystems.

    Thanks to the use of delegates,there is usually no need to subclass the NSWindow.The NSWindow class has a delegate and sends messages to the delegate just before the window is resized,closed,or otherwise modified.When the window’s delegate receives messages sent by the window,the delegate can perform necessary application-specific processing such as checking to see if the window contains any unsaved changes before it is closed and if so,giving the user a chance to save the changes or cancel the operation.The dele- gate can be part of the controller subsystem and have little coupling to other subsystems. All the delegate has to do is implement the appropriate methods corresponding to mes- sages that the window will send to it.

    Using delegates simplifies application development. In many cases,this pattern is si- multaneously simpler to implement and more flexible than the alternative.The delegate is free to implement some,all,or none of the methods corresponding to delegate messages. A single object can be the delegate of multiple objects. For example,a single object might be the delegate for all of the windows in an application. Conversely,every window might have a different delegate,or the delegate might be changed at runtime.

 

 

 

Notifications


    The Notification pattern enables communication between objects without tight cou- pling.An object is able to broadcast information to any number of other objects without any specific information about the other objects.An instance of Cocoa’sNSNotification class encapsulates the information to be broadcast. Objects that are interested in receiving the information register themselves with an instance of Cocoa’s NSNotificationCenter class. Registered objects are called observers,and the Notification pattern is sometimes called the “Observer” pattern in other frameworks. Registered observers specify the types of communication desired.

    When a notification is sent to a notification center,the notification center distributes the notification to appropriate observers.A single notification may be broadcast to any number of observers.The object that sends a message to a notification center doesn’t need to know what observers exist or how many observers ultimately receive the notification. Similarly,the observers don’t necessarily need to know where notifications originate.     

    The NSNotificationCenter class stores registered observers as Anonymous Objects using the Heterogeneous Container pattern described in Chapter 7,“AnonymousType and Heterogeneous Containers.” Notification and Delegation are related patterns,and Delegation is explained in Chapter 15,“Delegates.” Notification is also similar to the Key Value Observing pattern described in Chapter 32,“Bindings and Controllers.”

    Use the Notification pattern to establish anonymous communication between objects at runtime.Within the ModelView Controller design pattern,notifications safely cross sub- system boundaries without tying the subsystems together. Model objects often generate notifications that are ultimately received by controller objects,which react by updating view objects. In the other direction,model and controller objects observe notifications that may originate in the view or controller subsystems. For example,when a Cocoa ap- plication is about to terminate,the NSApplication controller object posts the NSApplicationWillTerminateNotification to the application’s default notification center. Model objects that need to perform clean-up processing before the application terminates register as observers to receive the NSApplicationWillTerminateNotification.

    Use the Notification pattern to broadcast messages. Notifications may be posted by any number of objects and received by any number of objects.The Notification pattern enables one-to-many and many-to-many relationships between objects.

Use the Notification pattern with Cocoa’s NSDistributedNotificationCenter class to achieve simple asynchronous interprocess communication.

    Use the Notification pattern when anonymous objects need to passively observe and react to important events. In contrast,use the Delegates pattern when anonymous objects need to actively influence events as they happen.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


我正在用TitaniumDeveloper编写一个应用程序,它允许我使用Javascript,PHP,Ruby和Python.它为API提供了一些可能需要的标准功能,但缺少的是全局事件.现在我想将全局热键分配给我的应用程序并且几乎没有任何问题.现在我只针对MAC,但无法找到任何Python或Ruby的解决方案.我找到了Coc
我的问题是当我尝试从UIWebView中调用我的AngularJS应用程序中存在的javascript函数时,该函数无法识别.当我在典型的html结构中调用该函数时,该函数被识别为预期的.示例如下:Objective-C的:-(void)viewDidLoad{[superviewDidLoad];//CODEGOESHERE_webView.d
我想获取在我的Mac上运行的所有前台应用程序的应用程序图标.我已经使用ProcessManagerAPI迭代所有应用程序.我已经确定在processMode中设置了没有modeBackgroundOnly标志的任何进程(从GetProcessInformation()中检索)是一个“前台”应用程序,并显示在任务切换器窗口中.我只需要
我是一名PHP开发人员,我使用MVC模式和面向对象的代码.我真的想为iPhone编写应用程序,但要做到这一点我需要了解Cocoa,但要做到这一点我需要了解Objective-C2.0,但要做到这一点我需要知道C,为此我需要了解编译语言(与解释相关).我应该从哪里开始?我真的需要从简单的旧“C”开始,正
OSX中的SetTimer在Windows中是否有任何等效功能?我正在使用C.所以我正在为一些软件编写一个插件,我需要定期调用一个函数.在Windows上,我只是将函数的地址传递给SetTimer(),它将以给定的间隔调用.在OSX上有一个简单的方法吗?它应该尽可能简约.我并没有在网上找到任何不花哨的东西
我不确定引擎盖下到底发生了什么,但这是我的设置,示例代码和问题:建立:>雪豹(10.6.8)>Python2.7.2(由EPD7.1-2提供)>iPython0.11(由EPD7.1-2提供)>matplotlib(由EPD7.1-2提供)示例代码:importnumpyasnpimportpylabasplx=np.random.normal(size=(1000,))pl.plot
我正在使用FoundationFramework在Objective-C(在xCode中)编写命令行工具.我必须使用Objective-C,因为我需要取消归档以前由NSKeyedArchiver归档的对象.我的问题是,我想知道我现在是否可以在我的Linux网络服务器上使用这个编译过的应用程序.我不确定是否会出现运行时问题,或者可
使用cocoapods,我们首先了解一下rvm、gem、ruby。rvm和brew一样,但是rvm是专门管理ruby的版本控制的。rvmlistknown罗列出ruby版本rvminstall版本号   可以指定更新ruby版本而gem是包管理gemsource-l查看ruby源gemsource-rhttps://xxxxxxxx移除ruby源gemsou
我有一个包含WebView的Cocoa应用程序.由于应用程序已安装客户群,我的目标是10.4SDK.(即我不能要求Leopard.)我有两个文件:index.html和data.js.在运行时,为了响应用户输入,我通常会使用应用程序中的当前数据填充data.js文件.(data.js文件由body.html上的index.html文件用于填充
如何禁用NSMenuItem?我点击后尝试禁用NSMenuItem.操作(注销)正确处理单击.我尝试通过以下两种方式将Enabled属性更改为false:partialvoidLogout(AppKit.NSMenuItemsender){sender.Enabled=false;}和partialvoidLogout(AppKit.NSMenuItemsender){LogoutI
我在想,创建一个基本上只是一个带Web视图的界面的Cocoa应用程序是否可行?做这样的事情会有一些严重的限制吗?如果它“可行”,那是否也意味着你可以为Windows应用程序做同样的事情?解决方法:当然可以创建一个只是一个Cocoa窗口的应用程序,里面有一个Web视图.这是否可以被称为“可可应
原文链接:http://www.cnblogs.com/simonshi2012/archive/2012/10/08/2715464.htmlFrom:http://www.idev101.com/code/Cocoa/Notifications.htmlNotificationsareanincrediblyusefulwaytosendmessages(anddata)betweenobjectsthatotherwi
如果不手动编写GNUmake文件,是否存在可以理解Xcode项目的任何工具,并且可以直接针对GNUstep构建它们,从而生成Linux可执行文件,从而简化(略微)保持项目在Cocoa/Mac和GNUstep/Linux下运行所需的工作?基本上,是否有适用于Linux的xcodebuild样式应用程序?几个星期前我看了pbtomake
我正在将页面加载到WebView中.该页面有这个小测试Javascript:<scripttype="text/javascript">functiontest(parametr){$('#testspan').html(parametr);}varbdu=(function(){return{secondtest:function(parametr){$('#testspan&#039
我正在尝试使用NSAppleScript从Objective-C执行一些AppleScript…但是,我正在尝试的代码是Yosemite中用于自动化的新JavaScript.它在运行时似乎没有做任何事情,但是,正常的AppleScript工作正常.[NSAppactivateIgnoringOtherApps:YES];NSAppleScript*scriptObject=[[NSApple
链接:https://pan.baidu.com/s/14_im7AmZ2Kz3qzrqIjLlAg           vjut相关文章Python与Tkinter编程ProgrammingPython(python编程)python基础教程(第二版)深入浅出PythonPython源码剖析Python核心编程(第3版)图书信息作者:Kochan,StephenG.出
我正在实现SWTJava应用程序的OSX版本的视图,并希望在我的SWT树中使用NSOutlineView提供的“源列表”选项.我通过将此代码添加到#createHandle()方法来破解我自己的Tree.class版本来实现这一点:longNSTableViewSelectionHighlightStyleSourceList=1;longhi=OS.sel_regist
我的Cocoa应用程序需要使用easy_install在用户系统上安装Python命令行工具.理想情况下,我想将一个bash文件与我的应用程序捆绑在一起然后运行.但据我所知这是不可能的,因为软件包安装在Python的“site-packages”目录中.有没有办法创建这些文件的“包”?如果没有,我应该如何运行ea
摘要: 文章工具 收藏 投票评分 发表评论 复制链接 Swing 是设计桌面应用程序的一个功能非常强大工具包,但Swing因为曾经的不足常常遭到后人的诟病.常常听到旁人议论纷纷,”Swing 运行太慢了!”,”Swing 界面太丑嘞”,甚至就是说”Swing 简直食之无味”. 从Swing被提出到现在,已是十年光景,Swing早已不是昔日一无是处的Swing了. Chris Adamson 和我写
苹果的开发:   我对于Linux/Unix的开发也是一窍不通,只知道可以用Java.不过接触了苹果过后,确实发现,世界上确实还有那么一帮人,只用苹果,不用PC的.对于苹果的开发,我也一点都不清楚,以下是师兄们整理出来的网站. http://www.chezmark.com/osx/    共享软件精选 http://www.macosxapps.com/    分类明了,更新及时的一个重要Mac