For example, allowing the user to drag an icon from one window to another requires some programming and familiarity with the NSDragging Implement your own objects by subclassing NSView or other classes.
When subclassing NSView , you write your own drawing methods using graphics functions. Subclassing requires a deeper understanding of how AppKit works. The AppKit framework consists of more than classes and protocols.
The diagrams in Figure show the inheritance relationships of the AppKit classes. As you can see, the hierarchy tree of AppKit is broad but fairly shallow; the classes deepest in the hierarchy are a mere five superclasses away from the root class and most classes are much closer than that.
Some of the major branches in this hierarchy tree are particularly interesting. This class defines the responder chain, an ordered list of objects that respond to user events. When the user clicks the mouse button or presses a key, an event is generated and passed up the responder chain in search of an object that can respond to it.
Any object that handles events must inherit from the NSResponder class. The noteworthy thing about this group of classes is that they roughly mirror the classes that inherit from NSControl , which inherits from NSView. For its user-interface objects that respond to user actions, AppKit uses an architecture that divides the labor between control objects and cell objects. The NSControl and NSCell classes, and their subclasses, define a common set of user-interface objects such as buttons, sliders, and browsers that the user can manipulate graphically to control some aspect of your application.
Most control objects are associated with one or more cell objects that implement the details of drawing and handling events. Controls and cells implement a mechanism that is based on an important design pattern of the AppKit: the target-action mechanism. A cell can hold information that identifies the message that should be sent to a particular object when the user clicks or otherwise acts upon the cell.
When a user manipulates a control by, for example, clicking it , the control extracts the required information from its cell and sends an action message to the target object. Target-action allows you to give meaning to a user action by specifying what the target object and invoked method should be. You typically use Interface Builder to set these targets and actions by Control-dragging from the control object to your application or other object.
You can also set targets and actions programmatically. Many objects in a user interface, such as text fields and table views, define a delegate. A delegate is an object that acts on behalf of, or in coordination with, the delegating object. It is thus able to impart application-specific logic to the operation of the user interface.
For more on delegation, target—action, and other paradigms and mechanisms of AppKit, see Communicating with Objects. For a discussion of the design patterns on which these paradigms and mechanisms are based, see Cocoa Design Patterns.
One of the general features of OS X v The system automatically scales content for rendering on the screen. The AppKit classes support resolution independence in their user-interface objects. However, for your own applications to take advantage of resolution independence, you might have to supply images at a higher resolution or make minor adjustments in your drawing code that take the current scaling factor into account.
The following sections briefly describe some of the capabilities and architectural aspects of the AppKit framework and its classes and protocols. It groups classes according to the class hierarchy diagrams shown in Figure The global application object. An NSApplication object has a delegate an object that you assign that is notified when the application starts or terminates, is hidden or activated, should open a file selected by the user, and so forth.
Windows and views. The view hierarchy is used for drawing and handling events within a window. An NSWindow object handles window-level events, distributes other events to its views, and provides a drawing area for its views. An NSWindow object also has a delegate allowing you to customize its behavior. Beginning with OS X v NSView is the superclass for all objects displayed in a window.
All subclasses implement a drawing method using graphics functions; drawRect: is the primary method you override when creating a new NSView. Controller classes for Cocoa bindings. This technology automatically synchronizes the application data stored in objects and the presentation of that data in a user interface. Panels dialogs.
For example, you would use an instance of NSPanel , rather than an instance of NSWindow , to display error messages or to query the user for a response to remarkable or unusual circumstances.
The AppKit implements some common dialogs for you such as the Save, Open, and Print dialogs, used to save, open, and print documents. Using these dialogs gives the user a consistent look and feel across applications for common operations.
Menus and cursors. Grouping and scrolling views. With the NSBox class, you can group elements in windows and draw a border around the entire group.
The NSSplitView class lets you append views vertically or horizontally, apportioning to each view some amount of a common territory; a sliding control bar lets the user redistribute the territory among views. The NSScrollView class and its helper class, NSClipView , provide a scrolling mechanism as well as the graphic objects that let the user initiate and control a scroll. The NSRulerView class allows you to add a ruler and markers to a scroll view. Table views and outline views.
The NSTableView class displays data in rows and columns. NSTableView is ideal for, but not limited to, displaying database records, where rows correspond to each record and columns contain record attributes.
The user can edit individual cells and rearrange the columns. You control the behavior and content of an NSTableView object by setting its delegate and data source objects. With the NSBrowser class you can create an object with which users can display and navigate hierarchical data. The Core Text framework provides a modern, low-level, high-performance technology for laying out text.
If you use the Cocoa text system, you should rarely have reason to use Core Text directly. The NSTextField class implements a simple editable text-input field, and the NSTextView class provides more comprehensive editing features for larger text bodies. NSTextView supports rich text, attachments graphics, file, and other , input management and key binding, and marked text attributes.
NSTextView works with the Fonts window and Font menu, rulers and paragraph styles, the Services facility, and the pasteboard Clipboard. The Cocoa text system also supports lists, tables, and noncontiguous selections. The NSFont class defines a single object for each distinct font; for efficiency, these objects, which can represent a lot of data, are shared by all the objects in your application.
The classes NSImage and NSImageRep encapsulate graphics data, allowing you to easily and efficiently access images stored in files on the disk and displayed on the screen. NSImageRep subclasses each know how to draw an image from a particular kind of source data.
The NSImage class provides multiple representations of the same image, and it also provides behaviors such as caching. The imaging and drawing capabilities of Cocoa are integrated with the Core Image framework. The other classes are mostly interface classes: They define and present panels and views that allow the user to select and apply colors. For example, the user can drag colors from the Colors window to any color well.
You can use the NSFileWrapper class to create objects that correspond to files or directories on disk. NSFileWrapper holds the contents of the file in memory so that it can be displayed, changed, or transmitted to another application. It also provides an icon for dragging the file or representing it as an attachment. You can use the NSFileManager class in the Foundation framework to access and enumerate file and directory contents.
Such applications can generate identical window containers that hold uniquely composed sets of data that can be stored in files. They have built-in or easily acquired capabilities for saving, opening, reverting, closing, and managing these documents. If an application is to be used in more than one part of the world, its resources may need to be customized, or localized, for language, country, or cultural region.
For example, an application may need to have separate Japanese, English, French, and German versions of character strings, icons, nib files, or context help. Resource files specific to a particular language are grouped together in a subdirectory of the bundle directory the directories with the. Usually you set up localization resource files using Interface Builder. See Internationalization and Localization Guide for more information on the Cocoa internationalization facilities.
This system interprets keystrokes generated by various international keyboards and delivers the appropriate text characters or Control-key events to text view objects. The AppKit provides operating-system support for your application through classes that implement the following features:. Sharing data with other applications. With very little programming on your part, custom view objects can be dragged and dropped anywhere.
Objects become part of this dragging mechanism by conforming to NSDragging The AppKit hides all the details of tracking the cursor and displaying the dragged image. Spell Checking. The NSSpellServer class lets you define a spell-checking service and provide it as a service to other applications.
To connect your application to a spell-checking service, you use the NSSpellChecker class. Its purpose is essentially the same: to provide all the classes that an application needs to construct and manage its user interface. However, there are significant differences in how the frameworks realize this purpose. One of the greatest differences is that, in iOS, the objects that appear in the user interface of a Cocoa application look and behave in a way that is different from the way their counterparts in a Cocoa application running in OS X look and behave.
Some common examples are text views, table views, and buttons. In addition, the event-handling and drawing models for Cocoa applications on the two platforms are significantly different. The following sections explain the reasons for these and other differences. Use the Interface Builder development application to drag windows, views, and other objects from an object library.
Figure presents the classes of the UIKit framework in their inheritance relationship. UIResponder also defines the interface and default behavior if any for event-handling methods and for the responder chain, which is a chain of objects that are potential event handlers.
When the user scrolls a table view with their finger or types characters in a virtual keyboard, UIKit generates an event and that event is passed up the responder chain until an object handles it. Controls in UIKit—that is, all objects that inherit from UIControl —do not require cells to carry out their primary role: sending action messages to a target object.
Yet the way UIKit implements the target-action mechanism is different from the way it is implemented in AppKit. The UIControl class defines a set of event types for controls; if, for example, you want a button UIButton to send an action message to a target object, you call UIControl methods to associate the action and target with one or more of the control event types.
When one of those events happens, the control sends the action message. Yet the UIKit implementation of delegation is different. Instead of using informal protocols, UIKit uses formal protocols with possibly some protocol methods marked optional. Each application running in iOS is managed by a singleton application object, and this object has a job that is almost identical to that for the global NSApplication object. The UIApplication object also receives notification of system-level and application-level events.
Many of these it passes to its delegate, allowing it to inject application-specific behavior when the application launches and terminates, to respond to low-memory warnings and changes in time, and to handle other tasks.
In OS X, the mouse and keyboard generate most user events. AppKit uses NSEvent objects to encapsulate these events. But finger touches are different in nature from mouse clicks; two or more touches occurring over a period could form a discrete event—a pinch gesture, for example.
The model for distributing and dispatching events to objects that can handle them on the two platforms is almost identical.
However, to handle an event, an object must take into consideration the sequence of touches specific to that event. UIKit also has gesture recognizers, objects that automate the detection of touches as gestures. A gesture recognizer analyzes a series of touches and, when it recognizes its gesture, sends an action message to a target.
UIKit provides ready-made gesture recognizers for gestures such as tap, swipe, rotate, and pan. You can also create custom gesture recognizers that detect application-specific gestures. Animation is integrated into the UIKit drawing implementation. The programmatic support that UIKit directly provides for drawing is a bit more limited compared to AppKit.
The framework offers classes and functions for Bezier paths, PDF generation, and simple line and rectangle drawing through functions declared in UIGraphics. You use UIColor objects to set colors in the current graphics context and UIImage objects to represent and encapsulate images. Because of the nature of the device—specifically the smaller screen size and the use of fingers instead of the mouse and keyboard for input—user-interface objects in iOS must typically be larger to be an adequate target for touches while at the same time make as efficient use of screen real estate as possible.
These objects are sometimes based on visual and tactile analogs of an entirely different sort. As an example, consider the date picker object, which is instantiated from a class that both the UIKit and AppKit frameworks define. In OS X, the date picker looks like this:. This style of date picker has a two tiny areas for incrementing date components, and thus is suited to manipulation by a mouse pointer. Contrast this with the date picker seen in iOS applications:.
This style of date picker is more suited for finger touches as an input source; users can swipe a month, day, or year column to spin it to a new value. The subclasses of UIControl instantiate objects that let users communicate their intent to an application.
Modal views. Scroll views. The UIScrollView class enables instances of its subclasses to respond to touches for scrolling within large views. As users scroll, the scroll view displays transient indicators of position within the document. The subclasses of UIScrollView implement table views, text views, and web views. Toolbars, navigation bars, split views, and view controllers. The UIViewController class is a base class for managing a view. A view controller provides methods for creating and observing views, overlaying views, handling view rotation, and responding to low-memory warnings.
You use toolbar UIToolbar objects to switch between modes or views of an application; you can also use them to display a set of functions that perform some action related to the current main view. These classes adopt the UITextInputTraits protocol to specify the appearance and behavior of the virtual keyboard that is presented when users touch the text-entry object; any subclasses that enable entry of text should also conform to this protocol.
And with the UIFont class you can specify the font characteristics of text in all objects that display text, including table cells, navigation bars, and labels. Applications that do their own text layout and font management can adopt the UITextInput protocol and use related classes and protocols to communicate with the text input system of iOS. These similarly named classes fulfill mostly similar roles, but there are differences. These differences can be a matter of scope, of inheritance, or of design.
Table describes the differences between the major classes in each framework. The classes are strikingly similar in their primary roles. However, the NSApplication class performs functions for example, managing application suspension, reactivation, and hiding that are not available to an iOS application. These classes also have nearly identical roles.
They are abstract classes that define an interface for responding to events and managing the responder chain. The main difference is that the NSResponder event-handling methods are defined for the mouse and keyboard, whereas the UIResponder methods are defined for the Multi-Touch event model.
It also provides an area for displaying views, dispatches events to those views, and converts between window and view coordinates. These classes are very similar in purpose and in their basic sets of methods. They allow you to move and resize views, manage the view hierarchy, draw view content, and convert view coordinates.
The design of UIView , however, makes view objects inherently capable of animation. Both classes define a mechanism for objects such as buttons and sliders so that, when manipulated, the control object sends an action message to a target object. The classes implement the target-action mechanism in different ways, largely because of the difference between event models. See The Target-Action Mechanism for information.
The role of both of these classes is, as their names suggest, to manage views. How they accomplish this task is different. UIViewController objects are used in the iOS application model for modal and navigation user interfaces for example, the views controlled by navigation bars.
More importantly, NSTableView objects support multiple columns of data; UITableView objects display only a single column of data at a time, and thus function more as lists than presentations of tabular data. Among the minor classes you can find some differences too. For example, UIKit has the UITextField and UILabel classes, the former for editable text fields and the latter for noneditable text fields used as labels; with the NSTextField class you can create both kinds of text fields simply by setting text-field attributes.
Core Data is a Cocoa framework that provides an infrastructure for managing object graphs, including support for persistent storage in a variety of file formats. Object-graph management includes features such as undo and redo, validation, and ensuring the integrity of object relationships. Object persistence means that Core Data saves model objects to a persistent store and fetches them when required.
Core Data is ideally suited for applications that act as front ends for relational databases, but any Cocoa application can take advantage of its capabilities. The central concept of Core Data is the managed object.
A managed object is simply a model object that is managed by Core Data, but it must be an instance of the NSManagedObject class or a subclass of that class. You describe the managed objects of your Core Data application using a schema called a managed object model. The Xcode application includes a data modeling tool to assist you in creating these schemas.
Each description specifies the attributes of an entity, its relationships with other entities, and metadata such as the names of the entity and the representing class. In a running Core Data application, an object known as a managed object context is responsible for a graph of managed objects. All managed objects in the graph must be registered with a managed object context.
The context allows an application to add objects to the graph and remove them from it. It also tracks changes made to those objects, and thus can provide undo and redo support. When a Core Data application wants to retrieve data from its external data store, it sends a fetch request—an object that specifies a set of criteria—to a managed object context. The managed object context returns the objects from the store that match the request after automatically registering them.
A managed object context also functions as a gateway to an underlying collection of Core Data objects called the persistence stack. The persistence stack mediates between the objects in your application and external data stores. The stack consists of two different types of objects, persistent stores and persistent store coordinators.
Persistent stores are at the bottom of the stack. They map between data in an external store—for example, an XML file—and corresponding objects in a managed object context. They don't interact directly with managed object contexts, however. Above a persistence store in the stack is a persistent store coordinator, which presents a facade to one or more managed object contexts so that multiple persistence stores below it appear as a single aggregate store.
Figure shows the relationships between objects in the Core Data architecture. A persistent-document object creates its own persistence stack and managed object context, mapping the document to an external data store. As part of a standard installation, Apple includes, in addition to the core frameworks for both platforms, several frameworks that vend Cocoa programmatic interfaces.
You can use these secondary frameworks to give your application capabilities that are desirable, if not essential. Some notable secondary frameworks include:. Sync Services— OS X only Using Sync Services you can sync existing contacts, calendars and bookmarks schemas as well as your own application data.
Tensions exist in this uneasily relationship. Yet, Apple developers largely see Apple as a partner that shares their values and their mission. For developers so opposed to corporate control in favor of creative freedom, why use tools provided by the largest IT corporation in the world? The answer, I believe, once again lies in affect. Indie Cocoa developers love using the Cocoa toolkit for programming, above and beyond other programming toolkits. But why? So, why do developers love Cocoa?
Firstly, Cocoa is fun to use, enjoyable and pleasurable, and not as frustrating or complex as other programming environments, although it can take a significant period of learning and adjustment to get used to it. Cocoa developers are almost all Mac or iOS users, first and foremost, and are self-selected — they want to program with Cocoa because they want to make apps for the Mac or iOS, and they love Apple because they make beautiful products, and they want to make beautiful works of art too.
This is an objective advantage allowing an individual programmer to write an application with the functionality of competing applications from corporate firms like Microsoft and Adobe, which employ hundreds of programmers for a single app. But it is also a source of the pleasure that they experience. It's like a musical instrument… Same with Objective- C.
So I've achieved mastery in the language, …so… going from, here is what I want to do thought-wise, to the code that does it, is a very direct process. It's not error-prone, because I've done it a lot and… the results are fairly fast to get. I can go from idea to something running… fairly quickly because the surface area of the language is very small… And then the Cocoa toolkit, it is… magnificently well-designed.
This lack of frustration in using the tool helps one achieve results quickly and boosts productivity. When NeXT was as struggling company with almost no marketshare, devoted NeXT developers had to rationalize why they refused to program for what they considered to be inferior systems.
One developer asserted that it was always a purely objective decision based on what made him more productive. Wil Shipley 4- Current Cocoa developers talk about a conversion experience, in which they saw the light of how Cocoa could make a programmer more productive, and subsequently became evangelists.
But then a coworker discovered Cocoa. And I kept trying to spread the Cocoa love around anyone who would listen. Developers who have programmed apps for both iOS and Android have complained not only about the fragmentation of the Android platform, but by the inconsistency of its APIs—concepts that are similar in different parts of Android have completely different names, as if the teams that designed them did not communicate or coordinate with each other for the benefit of their users which are developers.
Similarly, the multiplicity of different APIs on Microsoft to do the same thing, each with different nomenclature and different mental models of how things should be done, attests to the corporate culture within Microsoft, in which managers acquire power within the company by competing against rivals, resulting in a constant churn of new APIs incompatible with the old. This takes a level of commitment to coordination throughout the company, a commitment that neither Google nor Microsoft, let alone the open source community, has been able to attain.
This means options for user and developer configuration and tinkering are explicitly blocked off in favor of simplicity and consistency. And the only way to achieve consistency is to be absolutely draconic about options, and cutting them off, and refusing to allow things… Steve [Jobs] has a very famous quote I think about it being important to say no, or the importance of saying no to most things. I think we do share at least a few values with Apple and Apple employees. Brent Simmons Keeping things simple, and making them beautiful require absolute creative control.
None of the indies I spoke to were opposed to getting rich, per se, and many were indeed wealthy, though none of them were billionaires. The Cocoa application layer is primarily responsible for the appearance of apps and their responsiveness to user actions. In addition, many of the features that define the OS X user experience—such as Notification Center, full-screen mode, and Auto Save—are implemented by the Cocoa layer. The term Aqua refers to the overall appearance and behavior of OS X.
The Aqua look and feel is characterized by consistent, user-friendly behaviors combined with a masterful use of layout, color, and texture.
Although much of the Aqua look and feel comes for free when you use Cocoa technologies to develop your app, there are still many steps you should take to distinguish your app from the competition. To create a beautiful, compelling app that users will love, be sure to follow the guidance provided in OS X Human Interface Guidelines.
The Cocoa Application layer implements many features that are distinctive aspects of the OS X user experience. Notification Center provides a way for users to receive and view app notifications in an attractive, unobtrusive way. The Notification Center APIs, which help you configure the user-visible portions of a notification item, schedule items for delivery, and find out when items have been delivered.
You can also determine whether your app has launched as a result of a notification, and if it has, whether that notification is a local or remote that is, push notification. To ensure that your app gives users the best Notification Center experience, read Notification Center. Game Center accesses the same social-gaming network as on iOS, allowing users to track scores on a leaderboard, compare their in-game achievements, invite friends to play a game, and start a multiplayer game through automatic matching.
Game Center functionality is provided in three parts:. The Game Center app, in which users sign in to their account, discover new games and new friends, add friends to their gaming network, and browse leaderboards and achievements. The Game Kit framework, which contains the APIs developers use to support live multiplayer or turn-based games and adopt other Game Center features, such as in-game voice chat and leaderboard access.
The online Game Center service supported by Apple, which performs player authentication, provides leaderboard and achievement information, and handles invitations and automatching for multiplayer games.
In your game, use the Game Kit APIs to post scores and achievements to the Game Center service and to display leaderboards in your user interface. The sharing service provides a consistent user experience for sharing content among many types of services.
For example, a user might want to share a photo by posting it in a Twitter message, attaching it to an email, or sending it to another Mac user via AirDrop. As a result, you can display a custom UI to present the services. You can also use the NSSharingServicePicker class to display a list of sharing services including custom services that you define from which the user can choose.
When a service is performed, the system-provided sharing window is displayed, where the user can comment or add recipients. Resume is a systemwide enhancement of the user experience that supports app persistence. A user can log out or shut down the operating system, and on next login or startup, OS X automatically relaunches the apps that were last running and restores the windows that were last opened.
If your app provides the necessary support, reopened windows have the same size and location as before; in addition, window contents are scrolled to the previous position and selections are restored. To support app persistence, you must also implement automatic and sudden app termination, user interface preservation, and Auto Save. When an app enters full-screen mode it opens its frontmost app or document window in a separate space. Enabling full-screen mode adds an Enter Full Screen menu item to the View menu or, if there is no View menu, to the Window menu.
When a user chooses this menu item, the frontmost app or document window fills the entire screen. The AppKit framework provides support for customizing the appearance and behavior of full-screen windows. For example, you can set a window-style mask and can implement custom animations when an app enters and exits full-screen mode.
It expresses a larger class of relationships and is more intuitive to use than springs and struts. A view object usually knows best about its standard size and its positioning within its superview and relative to its sibling views.
A controller can override these values if something nonstandard is required. The entities you use to define a layout are Objective-C objects called constraints. You define constraints by combining attributes—such as leading, trailing, left, right, top, bottom, width, and height—that encapsulate the relationships between UI elements. Leading and trailing are similar to left and right, but they are more expressive because they automatically mirror the constraint in a right-to-left environment.
In addition, you can assign priority levels to constraints, to identify the constraints that are most important to satisfy. You can use Interface Builder to add and edit constraints for your interface. When you need more control, you can work with constraints programatically. A popover is a view that displays additional content related to existing content onscreen.
AppKit provides the NSPopover class to support popovers. You configure the appearance and behavior of a popover, including which user interactions cause the popover to close. And by implementing the appropriate delegate method, you can configure a popover to detach itself and become a separate window when a user drags it. OS X programs commonly use property list files also known as plist files to store configuration data.
A property list is a text or binary file used to manage a dictionary of key-value pairs.
0コメント