Tuesday, 19 February 2013

Copy, Cut, and Paste Operations | iPhone Apps Tutorial pdf

Copy, Cut, and Paste Operations

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  UIWebView 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.
Note: For usage guidelines related to copy and paste operations, see “Supporting Copy and Paste” in iPhone Human Interface Guidelines.

=> 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 UIMenuController 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 UIResponder class declares the method canPerformAction:withSender:. Responder classes can implement this method to show and remove commands of the editing menu based on the current context.
■ The UIResponderStandardEditActions 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 UIResponderStandardEditActions 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;
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 application pasteboards. Pasteboards must have unique names. UIPasteboard defines two system pasteboards, each with its own name and purpose:
■ UIPasteboardNameGeneral 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 generalPasteboard class method.
■ UIPasteboardNameFind is for search operations. The string currently typed by the user in the search bar (UISearchBar) is written to this pasteboard, and thus can be shared between applications. You can obtain an object representing the Find pasteboard by calling the pasteboardWithName:create: class method, passing in UIPasteboardNameFind for the name.
Typically you use one of the system-defined pasteboards, but if necessary you can create your own application pasteboard using pasteboardWithName:create: If you invoke pasteboardWithUniqueName, UIPasteboard 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 is supports (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 more information on UTIs, see Uniform Type Identifiers Overview.
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, as shown in Figure.
                                             Figure: 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 custom objects. 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.
Note: Touch events and techniques for handling them are discussed in “Touch Events”.
 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 setTargetRect: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.
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 becomeFirstResponder message to ensure that it is the first responder for the subsequent copy, cut, and paste operations.
 Displaying the editing menu
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *theTouch = [touches anyObject];
if ([theTouch tapCount] == 2 && [self becomeFirstResponder]) {
// selection management code goes here...
// bring up editing menu.
UIMenuController *theMenu = [UIMenuController sharedMenuController];
CGRect selectionRect = CGRectMake(currentSelection.x, currentSelection.y,
SIDE, SIDE);
[theMenu setTargetRect:selectionRect inView:self];
[theMenu setMenuVisible:YES animated:YES];
}
}
The menu initially includes all commands for which the first responder has corresponding UIResponderStandardEditActions 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 canPerformAction:withSender: method, or does not handle the given command, the message travels up the responder chain.
Program shows an implementation of the canPerformAction: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
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
BOOL retValue = NO;
ColorTile *theTile = [self colorTileForOrigin:currentSelection];
if (action == @selector(paste:) )
retValue = (theTile == nil) &&
[[UIPasteboard generalPasteboard] containsPasteboardTypes:
[NSArray arrayWithObject:ColorTileUTI]];
else if ( action == @selector(cut:) || action == @selector(copy:) )
retValue = (theTile != nil);
else
retValue = [super canPerformAction:action withSender:sender];
return retValue;
}
 
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 canPerformAction:withSender: on the first responder.
   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.
Note: Because UIResponderStandardEditActions is an informal protocol, any class in your application can implement its methods. But to take advantage of the default behavior for traversing the responder chain, the class implementing the methods should inherit from UIResponder and should be installed in the responder chain.
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):

1. 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, 
2. 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 a selected image, you could use the UIImageJPEGRepresentation and UIImagePNGRepresentation functions to convert the image to a different representation.
3. Obtain a pasteboard object.
In many cases, this is the general pasteboard, which you can get through the generalPasteboard class method.
4. Assign a suitable UTI for each representation of data written to the pasteboard item.
5. Write the data to the first pasteboard item for each representation type:
■ To write a data object, send a setData:forPasteboardType: message to the pasteboard object.
■ To write a property-list object, send a setValue:forPasteboardType: message to the pasteboard object.
6. If the command is Cut (cut: method), remove the object represented by the selection from the application’s data model and update your view.
Program 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
- (void)copy:(id)sender {
UIPasteboard *gpBoard = [UIPasteboard generalPasteboard];
ColorTile *theTile = [self colorTileForOrigin:currentSelection];
if (theTile) {
NSData *tileData = [NSKeyedArchiver archivedDataWithRootObject:theTile];
if (tileData)
[gpBoard setData:tileData forPasteboardType:ColorTileUTI];
}
}
- (void)cut:(id)sender {
[self copy:sender];
ColorTile *theTile = [self colorTileForOrigin:currentSelection];
if (theTile) {
CGPoint tilePoint = theTile.tileOrigin;
[tiles removeObject:theTile];
CGRect tileRect = [self rectFromOrigin:tilePoint inset:TILE_INSET];
[self setNeedsDisplayInRect:tileRect];
}
}

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 UIResponderStandardEditActions 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 generalPasteboard 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 canPerformAction:withSender:
3. If the first item of the pasteboard contains data that the application can handle, call one of the following methods to read it:
■ dataForPasteboardType: if the data to be read is encapsulated in an NSData object.
■ valueForPasteboardType: if the data to be read is encapsulated in a property-list object 
4. Add the object to the application’s data model.
5. Display a representation of the object in the user interface at the location specified by the user.
the below program  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
- (void)paste:(id)sender {
UIPasteboard *gpBoard = [UIPasteboard generalPasteboard];
NSArray *pbType = [NSArray arrayWithObject:ColorTileUTI];
ColorTile *theTile = [self colorTileForOrigin:currentSelection];
if (theTile == nil && [gpBoard containsPasteboardTypes:pbType]) {
NSData *tileData = [gpBoard dataForPasteboardType:ColorTileUTI];
ColorTile *theTile = (ColorTile *)[NSKeyedUnarchiver
unarchiveObjectWithData:tileData];
if (theTile) {
theTile.tileOrigin = self.currentSelection;
[tiles addObject:theTile];
CGRect tileRect = [self rectFromOrigin:currentSelection
inset:TILE_INSET];
[self setNeedsDisplayInRect:tileRect];
}
}
}

No comments: