Copy, Cut, and Paste Operations IPHONE APPS

Beginning with iPhone OS 3.0, users can now copy text, images, or other data in one application and paste that data to another location within the same application or in a different application. You can, for example, copy a person’s address in an email message and paste it into the appropriate field in the Contacts application. The UIKit framework currently implements copy-cut-paste in the UITextView, UITextField, and UI WebView classes. If you want this behavior in your own applications, you can either use objects of these classes or implement copy cut paste yourself.

The following sections describe the programmatic interfaces of the UIKit that you use for copy, cut, and paste operations and explain how they are used.

UIKit Facilities for Copy-Paste Operations

Several classes and an informal protocol of the UIKit framework give you the methods and mechanisms you need to implement copy, cut, and paste operations in your application:

  • The UIPasteboard class provides pasteboards: protected areas for sharing data within an application or between applications. The class offers methods for writing and reading items of data to and from a pasteboard.
  • The UI Menu Controller class displays an editing menu above or below the selection to be copied, cut, or pasted into. The commands of the editing menu are (potentially) Copy, Cut, Paste, Select, and Select All.
  • The UI Responder class declares the method can Perform Action: withSender: Responder classes can implement this method to show and remove commands of the editing menu based on the current context.
  • The UI Responder Standard Edit Actions informal protocol declares the interface for handling copy, cut, paste, select, and select-all commands. When users tap one of the commands in the editing menu, the corresponding UI Responder Standard Edit Actions method is invoked.

Pasteboard Concepts

A pasteboard is a standardized mechanism for exchanging data within applications or between applications. The most familiar use for pasteboards is handling copy, cut, and paste operations:

  • When a user selects data in an application and chooses the Copy (or Cut) menu command, the selected data is placed onto a pasteboard.
  • When the user chooses the Paste menu command (either in the same or a different application), the data on a pasteboard is copied to the current application from the pasteboard.

In iPhone OS, a pasteboard is also used to support Find operations. Additionally, you may use pasteboards to transfer data between applications using custom URL schemes instead of copy, cut, and paste commands; see “Communicating with Other Applications” for information about this technique.

Regardless of the operation, the basic tasks you perform with a pasteboard object are to write data to a pasteboard and to read data from a pasteboard. Although these tasks are conceptually simple, they mask a number of important details. The main complexity is that there may be a number of ways to represent data, and this complexity leads to considerations of efficiency. These and other issues are discussed in the following sections.

Named Pasteboards

Pasteboards may be public or private. Public pasteboard are called system pasteboards; private pasteboards are created by applications, and hence are called applicationpasteboards. Pasteboards must have unique names. UIPasteboard defines two system pasteboards, each with its own name and purpose:

  • UI Pasteboard Name General is for cut, copy, and paste operations involving a wide range of data types. You can obtain a singleton object representing the General pasteboard by invoking the general Pasteboard class method.
  • UI Paste board Name Find is for search operations. The string currently typed by the user in the search bar (UI Search Bar) is written to this pasteboard, and thus can be shared between applications. You can obtain an object representing the Find pasteboard by calling the paste board With Name:create: class method, passing in UI Paste board Name Find for the name.

Typically you use one of the system-defined pasteboards, but if necessary you can create your own application pasteboard using pasteboard With Name: create: If you invoke paste board With Unique Name, UI Pasteboard gives you a uniquely-named application pasteboard. You can discover the name of a pasteboard through its name property.

Pasteboard Persistence

Pasteboards can be marked persistent so that they continue to exist beyond the termination of applications that use them. Pasteboards that aren’t persistent are removed when the application that created them quits. System pasteboards are persistent. Application pasteboards by default are not persistent. To make an application pasteboard persistent, set its persistent property to YES. A persistent application pasteboard is removed when a user uninstalls the owning application.

Pasteboard Owner and Items

The object that last put data onto the pasteboard is referred to as the pasteboard owner. Each piece of data placed onto a pasteboard is considered a pasteboard item. The pasteboard can hold single or multiple items. Applications can place or retrieve as many items as they wish. For example, say a user selection in a view contains both text and an image. The pasteboard lets you copy the text and the image to the pasteboard as separate items. An application reading multiple items from a pasteboard can choose to take only those items that issupports (the text, but not the image, for example).

Representations and UTIs

Pasteboard operations are often carried out between two different applications. Neither application is required to know about the other, including the kinds of data it can handle. To maximize the potential for sharing, a pasteboard can hold multiple representations of the same pasteboard item. For example, a rich text editor might provide HTML, PDF, and plain-text representations of the copied data. An item on a pasteboard includes all representations of that data item that the application can provide.

Each representation of a pasteboard item is typically identified by a Unique Type Identifier (UTI).(A UTI is simply a string that uniquely identifies a particular data type. The UTI provides a common means to identify data types. If you have a custom data type you wish to support, you must create a unique identifier for it. For this, you could use reverse-DNS notation for your representation-type string to ensure uniqueness; for example, a custom representation type could be com.myCompany.myApp.myType.

For example, suppose an application supported selection of rich text and images. It may want to place on a pasteboard both rich text and Unicode versions of a text selection and different representations of an image selection. Each representation of each item is stored with its own data,

Pasteboard items and representations

Pasteboard items and representations

In general, to maximize the potential for sharing, pasteboard items should include as many different representations as possible.

A pasteboard reader must find the data type that best suits its capabilities (if any). Typically, this means selecting the richest type available. For example, a text editor might provide HTML (rich text) and plain-text representations of copied text data. An application that supports rich text should retrieve the HTML representation and an application that only supports plain text should retrieve the plain-text version.

Change Count

The change count is a per-pasteboard variable that increments every time the contents of the pasteboard changes—specifically, when items are added, modified, or removed. By examining the change count (through the changeCount property), an application can determine whether the current data in the pasteboard is the same as the data it last received. Every time the change count is incremented, the pasteboard sends a notification to interested observers.

Selection and Menu Management

To copy or cut something in a view, that “something” must be selected. It can be a range of text, an image, a URL, a color, or any other representation of data, including customobjects. To implement copy-and-paste behavior in your custom view, you must manage the selection of objects in that view yourself. If the user selects an object in the view by making a certain touch gesture (for example, a double-tap) you must handle that event, internally record the selection (and deselect any previous selection), and perhaps visually indicate the new selection in the view. If it is possible for users to select multiple objects in your view for copy-cut-paste operations, you must implement that multiple-selection behavior.

When your application determines that the user has requested the editing menu—which could be the action of making a selection—you should complete the following steps to display the menu:

  1. Call the sharedMenuController class method of UIMenuController to get the global menu-controller instance.
  2. Compute the boundaries of the selection and with the resulting rectangle call the set TargetRect: inView: method. The editing menu is displayed above or below this rectangle, depending how close the selection is to the top or bottom of the screen.
  3. Call the setMenuVisible:animated: method (with YES for both arguments) to animate the display of the editing menu above or below the selection.

Listing illustrates how you might display the edit menu in an implementation of the touchesEnded: withEvent: method. (Note that the example omits the section of code that handles the selection.) This code snippet also shows that the custom view sending itself a become First Responder message to ensure that it is the first responder for the subsequent copy, cut, and paste operations.

Displaying the editing menu

The menu initially includes all commands for which the first responder has corresponding UI Responder Standard Edit Actions method implementations (copy:, paste:, and so on). Before the menu is displayed, however, the system sends a canPerformAction:withSender: message to the first responder, which in many cases is the custom view itself. In its implementation of this method, the responder evaluates whether the command (indicated by the selector in the first argument) is applicable in the current context. For example, if the selector is paste: and there is no data in the pasteboard of a type the view can handle, the responder should return NO to suppress the Paste command. If the first responder does not implement the can PerformAction: withSender: method, or does not handle the given command, the message travels up the responder chain.

Listing shows an implementation of the can Perform Action: withSender: method that looks for message matching the copy:, copy:, and paste: selectors; it enables or disables the Copy, Cut, and Paste menu commands based on the current selection context and, for paste, the contents of the pasteboard.

Conditionally enabling menu commands

Note that the final else clause in this method calls the superclass implementation to give any superclasses a chance to handle commands that the subclass chooses to ignore.

Note that a menu command, when acted upon, can change the context for other menu commands. For example, if the user selects all objects in the view, the Copy and Cut commands should be included in the menu. In this case the responder can, while the menu is still visible, call update on the menu controller; this results in the reinvocation of can
Perform Action: with Sender: on the first responder.

Copying and Cutting the Selection

When users tap the Copy or Cut command of the editing menu, the system invokes the copy: or cut: method (respectively) of the responder object that implements it. Usually the first responder—your custom view—implements these methods, but if the first responder doesn’t implement them, the message travels up the responder in the usual fashion. Note that the UIResponderStandardEditActions informal protocol declares these methods.

In response to a copy: or cut: message, you write the object or data represented by the selection to the pasteboard in as many different representations as you can. This operation involves the following steps (which assume a single pasteboard item):

  • From the selection, identify or obtain the object or the binary data corresponding to the object. Binary data must be encapsulated in an NSData object. If you’re going to write another type of object to the pasteboard, it must be a property-list object— that is, an object of one of the following classes: NSString, NSArray, NSDictionary, NSDate, NSNumber, or NSURL. (For more on property-list objects, see Property List Programming Guide.)
  • If possible, generate one or more other representations of the object or data. For example, if in the previous step you created a UIImage object representing selected image, you could use the UI Image JPEG Representation and UI Image PNG Representation functions to convert the image to a different representation.
  • Obtain a pasteboard object.
    In many cases, this is the general pasteboard, which you can get through the general Pasteboard class method.
  • Assign a suitable UTI for each representation of data written to the pasteboard item. See “Pasteboard Concepts” for a discussion of this subject.
  • Write the data to the first pasteboard item for each representation type:
  • To write a data object, send a set Data: for Pasteboard Type: message to the pasteboard object.
  • To write a property-list object, send a setValue: for Pasteboard Type: message to the pasteboard object.
  • If the command is Cut (cut: method), remove the object represented by the selection from the application’s data model and update your view.

Listing shows implementations of the copy: and cut: methods. The cut: method invokes the copy: method and then removes the selected object from the view and the data model. Note that the cut: method archives a custom object to obtain an NSData object that it can pass to the pasteboard in setData:forPasteboardType:.

Copying and cutting operations

Pasting the Selection

When users tap the Paste command of the editing menu, the system invokes the paste: method of the responder object that implements it. Usually the first responder— your custom view—implements this method, but if the first responder doesn’t implement it, the message travel up the responder in the usual fashion. The paste: method is declared by the UI Responder Standard Edit Actions informal protocol.

In response to a paste: message, you read an object from the pasteboard in a representation that your application supports. Then you add the pasted object to the application’s data model and display the new object in the view in the user-indicated location. This operation involves the following steps (which assume a single pasteboard item):

  1. Obtain a pasteboard object.
    In many cases, this is the general pasteboard, which you can get through the general Pasteboard class method.
  2. Verify that the first pasteboard item contains data in a representation that your application can handle by calling the containsPasteboardTypes: method or the pasteboardTypes method and then examining the returned array of types.
    Note that you should have already performed this step in your implementation of can Perform Action: with Sender:.
  3. If the first item of the pasteboard contains data that the application can handle, call one of the following methods to read it:
    • data For Pasteboard Type: if the data to be read is encapsulated in an NSData object.
    • value For Pasteboard Type:if the data to be read is encapsulated in a property-list object (see “Copying and Cutting the Selection”).
    • Add the object to the application’s data model.
    • Display a representation of the object in the user interface at the location specified by the user.

Listing is an example of an implementation of the paste: method. It does the reverse of the combined cut: and copy: methods. The custom view first sees whether the general pasteboard holds its custom representation of data; if it does, it then reads the data from the pasteboard, adds it to the application’s data model, and marks part of itself—the current selection—for redrawing.

Pasting data from the pasteboard to a selection

Dismissing the Editing Menu

When your implementation of the cut:, copy: or paste: command returns, the editing menu is automatically hidden. You can keep it visible with the following line of code:

[UIMenuController setMenuController].menuVisible = YES;

The system may hide the editing menu at any time. For example, it hides the menu when an alert is displayed or the user taps in another area of the screen. If you have state or a display that depends on whether the editing menu is visible, you should listen for the notification named UI Menu Controller Will Hide Menu Notification and take an appropriate action.


Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

IPHONE APPS Topics