To avoid such problems - delete the import statement or - insert an import statement above the cocoa. Stack Overflow for Teams — Collaborate and share knowledge with a private group.
Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. Ask Question. Asked 11 years, 3 months ago. Active 8 years, 1 month ago. Viewed 8k times. Fabian Fabian 1 1 gold badge 10 10 silver badges 14 14 bronze badges. Add a comment. Active Oldest Votes. It seems fairly clear that those are the ones we should be using. I restarted Xcode and made myself a new project and found that the delegate files were present and correct.
I also noticed that the Cocoa Application project which had previously had the standard blue project icon now stood out with a separate icon:.
The values encapsulated by immutable objects cannot be modified after they are created, whereas the values encapsulated by mutable objects can be modified. Object Mutability discusses mutable and immutable objects in detail. The NSNumber class a subclass of NSValue instantiates objects that contain numeric values such as integers, floats, and doubles. Instances of the NSData class provides object-oriented storage for streams of bytes for example, image data.
The class has methods for writing data objects to the file system and reading them back. They offer methods for calculating date and time differences, for displaying dates and times in many formats, and for adjusting times and dates based on location in the world. Objects of the NSString class commonly referred to as strings are a type of value object that provides object-oriented storage for a sequence of Unicode characters. Methods of NSString can convert between representations of character strings, such as between UTF-8 and a null-terminated array of bytes in a particular encoding.
NSString also offers methods for searching, combining, and comparing strings and for manipulating file-system paths. The NSString class also has a few associated classes. Attributed strings, which are instances of the NSAttributedString class, manage ranges of characters that have attributes such as font and kerning associated with them.
Formatter objects—that is, objects derived from NSFormatter and its descendent classes—are not themselves value objects, but they perform an important function related to value objects. They convert value objects such as NSDate and NSNumber instances to and from specific string representations, which are typically presented in the user interface.
Collections are objects that store other objects in a particular ordering scheme for later retrieval. As with many of the value classes, these collection classes have immutable and mutable variants. For example, once you create an NSArray object that holds a certain number of elements, you cannot add new elements or remove existing ones; for that purpose you need the NSMutableArray class. To learn about mutable and immutable objects, see Object Mutability.
Objects of the major collection classes have some common behavioral characteristics and requirements. The items they contain must be objects, but the objects may be of any type. Collection objects, as with value objects, are essential components of property lists and, like all objects, can be archived and distributed.
Moreover, collection objects automatically retain—that is, keep a strong reference to—any object they contain. If you remove an object from a mutable collection, it is released, which results in the object being freed if no other object claims it. The collection classes provide methods to access specific objects they contain. In addition, there are special enumerator objects instances of NSEnumerator and language-level support to iterate through collections and access each element in sequence.
Arrays NSArray are ordered collections that use zero-based indexing for accessing the elements of the collection. Dictionaries NSDictionary are collections managing pairs of keys and values; the key is an object that identifies the value, which is also an object.
Because of this key-value scheme, the elements in a dictionary are unordered. Within a dictionary, the keys must be unique. Although they are typically string objects, keys can be any object that can be copied. Sets NSSet are similar to arrays, but they provide unordered storage of their elements instead of ordered storage. In other words, the order of elements in a set is not important.
In OS X, the Foundation framework includes several additional collection classes. NSMapTable is a mutable dictionary-like collection class; however, unlike NSDictionary , it can hold pointers as well as objects and it maintains weak references to its contained objects rather than strong references.
The NSHashTable class is modeled after NSSet but it can store pointers to functions and it provides different options, in particular to support weak relationships in a garbage-collected environment. For more on collection classes and objects, see Collections Programming Topics. The remaining classes of the Foundation framework fall into various categories, as indicated by the diagram in Figure The major categories of classes, shown in Figure , are described here:.
Operating-system services. Many Foundation classes facilitate access of various lower-level services of the operating system and, at the same time, insulate you from operating-system idiosyncrasies. For example, NSProcessInfo lets you query the environment in which an application runs and NSHost yields the names and addresses of host systems on a network. You can use an NSTimer object to send a message to another object at specific intervals, and NSRunLoop lets you manage the input sources of an application or other type of program.
NSUserDefaults provides a programmatic interface to a system database of global per-host and per-user default values preferences. File system and URL. NSFileManager provides a consistent interface for file operations such as creating, renaming, deleting, and moving files.
NSFileHandle permits file operations at a lower level for example, seeking within a file. NSBundle finds resources stored in bundles and can dynamically load some of them for example, nib files and code. NSThread lets you create multithreaded programs, and various lock classes offer mechanisms for controlling access to process resources by competing threads. You can use NSOperation and NSOperationQueue to perform multiple operations concurrent or nonconcurrent in priority and dependence order.
With NSTask , your program can fork off a child process to perform work and monitor its progress. Interprocess communication. Most of the classes in this category represent various kinds of system ports, sockets, and name servers and are useful in implementing low-level IPC. Bonjour is a powerful system for publishing and browsing for services on an IP network.
See the summary of the notification classes in Foundation Paradigms and Policies. Archiving and serialization. The classes in this category make object distribution and persistence possible.
NSCoder and its subclasses, along with the NSCoding protocol, represent the data an object contains in an architecture-independent way by allowing class information to be stored along with the data.
NSKeyedArchiver and NSKeyedUnarchiver offer methods for encoding objects and scalar values and decoding them in a way that is not dependent on the ordering of encoding messages. Objective-C language services. NSException and NSAssertionHandler provide an object-oriented way of making assertions and handling exceptions in code. An NSInvocation object is a static representation of an Objective-C message that your program can store and later use to invoke a message in another object; it is used by the undo manager NSUndoManager and by the distributed objects system.
An NSMethodSignature object records the type information of a method and is used in message forwarding. NSClassDescription is an abstract class for defining and querying the relationships and properties of a class. XML processing. Foundation on both platforms has the NSXMLParser class, which is an object-oriented implementation of a streaming parser that enables you to process XML data in an event-driven way.
Objects of these classes represent an XML document as a hierarchical tree structure. This approach lets you to query this structure and manipulate its nodes. Predicates and expressions. NSExpression objects represent expressions in a predicate. The following categories of classes are present only in the OS X version of Foundation:.
Spotlight queries. The classes in this category help to make your program responsive to AppleScript scripts and Apple event commands. Distributed objects. You use the distributed object classes for communication between processes on the same computer or on different computers on a network. AppKit is a framework containing all the objects you need to implement your graphical, event-driven user interface in OS X: windows, dialogs, buttons, menus, scrollers, text fields—the list goes on.
AppKit handles all the details for you as it efficiently draws on the screen, communicates with hardware devices and screen buffers, clears areas of the screen before drawing, and clips views.
The number of classes in AppKit may seem daunting at first. However, most AppKit classes are support classes that you use indirectly. You also have the choice at which level you use AppKit:. For this, you might use off-the-shelf controller objects for Cocoa bindings or you may need to implement one or more custom controller classes—particularly the action and delegate methods of those classes.
For example, you would need to implement a method that is invoked when the user chooses a menu item unless it has a default implementation that is acceptable. Control the user interface programmatically, which requires more familiarity with AppKit classes and protocols.
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. At that point we need to return the NSUndoManager from the core data managed object context unlike on iOS the OS X managed object context provides an undo manager by default. A final piece of setup code. We need to subclass our generic view controller and pass it the managed object context from our window controller.
To do that I deleted the view controller created by the Xcode template and added a new one named CountryTableViewController. As with the window controller make sure you only add this file to the OS X target. The public interface for the class has a single property for the managed object context:. Before we discuss that we just need to remember to update the storyboard to change the class of the view controller to CountryTableViewController.
Then back in the windowDidLoad method of our window controller we can retrieve our view controller from the contentController property and set the managed object context:. Now things start to get interesting. I should warn you that many an experienced OS X developer will warn you about using Cocoa bindings.
At this point in an iOS app we would probably add a subclass for the table view controller and implement the various table view delegate and data source methods. A similar approach will also work here but there is another more interesting way which saves us a lot of code.
Cocoa Bindings is an OS X only feature that allows you to connect a data object to a view object. For further details see Cocoa Bindings Programming Topics. It is possible to bind a view directly to a model object. In practise it is useful to have a controller object. AppKit supplies a number of controller classes all subclasses of NSController specifically to work with Cocoa Bindings.
These classes all provide easy ways to bind views to the currently selected object and also to supply placeholders values when the selection is empty. In our case we have a simple flat collection of objects so we will use an NSArrayController.
We want to bind the array controller to the columns in our table view so we need to add it to the view controller. Drag an Array Controller object from the Xcode object library to the view controller scene. It is not required but it can help to rename the Array Controller label that appears in Interface Builder.
For some reason the label does not always update in the document outline. If that happens a restart of Xcode seems to force the update:.
We want the array controller to be bound to Country objects from our core data managed object context:. Set the Prepares Content flag - this makes the array controller fetch the Country entity data when it is loaded from the storyboard. In the Bindings inspector second from last tab in the parameters section expand the Managed Object Context and bind it to the Country Table View Controller with a model key path of managedObjectContext :.
At this point we have our array controller bound to the managed object context in our view controller so that it can fetch, add and remove Country objects. In the storyboard document outline expand the table view and select the Country column. In the Bindings inspector bind the value to the CountriesArrayController this is where changing the label of the array controller is useful.
Make sure the Controller Key is set to arrangedObjects the NSArrayController property that has all of our Country objects and the Model Key Path is name which is the property of the Country object we want to display in this column:.
Repeat this process for each of the columns and text fields using the appropriate property name for the model key path.
0コメント