IOS copy, cut and paste theory basics

Source: Internet
Author: User
Tags response code reverse dns uikit

Brief introduction

After iphone OS 3.0, users can copy text, images, or other data on one application and paste them into different locations in the current or other application. For example, you can copy an address from an e-mail message and paste it into the Address field of the Contacts program. Currently, the UIKit Framework UITextView UITextField UIWebView implements copy-cut-paste support in,,, and classes. If you want to get this behavior in your own application, you can use the objects of these classes, or implement them yourself.

But after iOS7.0, Uipasteboard changed from shared to sandboxed ,Uipasteboard had no problem, but developers started using it to store identifiers, and the problem arose when they shared these identifiers with other relevant apps. One of the tricks that is used is openudid. After iOS7, use +[uipasteboard pasteboardwithname:create:] and +[uipasteboard Pasteboardwithuniquename] to create the clipboard, and only for the same app The group is visible, which makes openudid less useful.

The following sections of this article describe the programming interfaces used in Uikit for copy, cut, and paste operations, and explain their usage.

Copy, cut, and paste operations

After iphone OS 3.0, users can copy text, images, or other data on one application and paste them into different locations in the current or other application. For example, you can copy an address from an e-mail message and paste it into the Address field of the Contacts program. Currently, the UIKit Framework UITextView UITextField UIWebView implements copy-cut-paste support in,,, and classes. If you want to get this behavior in your own application, you can use the objects of these classes, or implement them yourself.

The following sections of this article describe the programming interfaces used in Uikit for copy, cut, and paste operations, and explain their usage.

Note: refer to the "Support Copy and paste" section in the iphone HMI guide documentation for usage guidelines related to copy and paste operations.

Facilities supporting copy-paste operation in Uikit

The Uikit framework provides several classes and an informal protocol to provide methods and mechanisms for copy, cut, and paste operations in an application. Specific as follows:

    • UIPasteboardclass provides an interface to the pasteboard. A pasteboard is a protected area that is used for data sharing within an application or across applications. This class provides a way to read and write data items on the Clipboard.

    • UIMenuControllerclass to display an Edit menu on the top and bottom sides of the selected copy, Cut, and paste objects. Commands on the Edit menu can be copied, cut, pasted, selected, and all selected.

    • UIResponderClass declares a canPerformAction:withSender: method. The responder class can implement this method to display or remove commands on the Edit menu based on the current context.

    • UIResponderStandardEditActionsThe informal protocol declares an interface for handling copy, cut, paste, select, and all selected commands. When the user touches a command on the Edit menu, the corresponding UIResponderStandardEditActions method is called.

The concept of an adhesive board

Pasteboard is a standardized mechanism for exchanging data within the same application or between different applications. The most common use of pasteboard is to handle copy, clip, and paste operations:

    • When the user selects the data in an application and selects the copy (or cut) menu command, the selected data is placed on the pasteboard.

    • When the user chooses to paste the command (which can be in the same or different application), the data on the pasteboard is copied to the current application.

In the iphone OS, the Pasteboard is also used to support the find operation. In addition, it can be used to transfer data between different applications through a custom URL type (instead of copying, cutting, and pasting commands, see the "communication between and other applications" section for information on this technique.)

Either way, the basic task that you perform through the pasteboard is to read and write the pasteboard data. Although these tasks are conceptually simple, they block a lot of important details. The main reason for the complexity is that there may be many ways in which data can be represented, and this complexity introduces efficiency considerations. These and other issues are discussed in the following sections of this article.

Name Pasteboard

The pasteboard may be public, or it may be private. The public pasteboard is called the system Pasteboard , and the private pasteboard is created by the application itself and is therefore called the application Pasteboard . The pasteboard must have a unique name. UIPasteboardTwo system pasteboard are defined, each with its own name and purpose:

    • UIPasteboardNameGeneralFor cut, copy, and paste operations, it involves a wide range of data types. You can use the class method of this class generalPasteboard to obtain a single object representing the Universal (General) pasteboard.

    • UIPasteboardNameFindUsed to retrieve the operation. The string that is typed by the current user in the search bar ( UISearchBar ) is written to the Clipboard, so it can be shared among different applications. You can pasteboardWithName:create: get an object that represents a clipboard retrieval by calling the class method and passing in the value in the name parameter UIPasteboardNameFind .

Typically, you just need to use the system-defined pasteboard. But if necessary, you can also pasteboardWithName:create: create your own application pasteboard by means of a method. If you call pasteboardWithUniqueName a method, UIPasteboard you are given an application pasteboard with a unique name. You can name obtain this name by its property declaration .

Persistent retention of the pasteboard

You can identify the pasteboard as persistent so that its contents continue to exist after the currently used application terminates. A non-persistent pasteboard is removed after its creation application exits. The system pasteboard is persisted, and the application pasteboard is not persisted by default. Set the properties of its application pasteboard persistent to YES keep it persistent. When the owner program of the persistent pasteboard is uninstalled by the user, it is also removed.

Owner and data item for Pasteboard

The object that finally puts the data on the pasteboard is called the owner of the pasteboard. Each piece of data placed on the pasteboard is called a pasteboard data item . The pasteboard can retain one or more data items. The application can put in or get the desired number of data items. For example, assume that the content that the user selects in the view contains some text and an image, and the pasteboard allows you to copy text and images as different items of data. Applications that read multiple data items from the pasteboard can choose to read only supported data items (such as text only, not images).

Important: When an application writes data to the pasteboard, even if it is a single data item, that data supersedes the Clipboard's current content. Although you might use UIPasteboard addItems: methods to add items, the Write method does not add those items after the current contents of the pasteboard.

Representation of data and UTI

Pasteboard operations are often performed between different applications. The system does not require the application to know the other person's information, including the kind of data that the other person can handle. To maximize the potential for data sharing, the Pasteboard retains multiple representations of the same data item. For example, a rich text editor can provide HTML, PDF, and plain text representations of the copied data. A data item on the pasteboard includes all the representations that the application can provide for that data.

Each representation of a pasteboard data item typically has a unique type identifier (unique Identifier, abbreviated as UTI). A UTI is simply defined as a string that uniquely identifies a particular data type. UTI provides a common means of identifying data types. If you want to support a custom data type, you must create a unique identifier for it. To do this, you can use reverse DNS notation to define a type identification string to ensure its uniqueness. For example, you can use it com.myCompany.myApp.myType to represent a custom type identity. For more information about UTI, see Unified Type Identifiers Overview .

As an example, suppose an application supports the selection of rich text and images, and it may want to place the selected text of rich text and Unicode versions, as well as the different representations of selected images, onto the pasteboard. In such a scenario, each representation of each data item is saved with its own data, as shown in 3-3.

Figure 3-3 Paste board and its representation

In general, in order to maximize potential sharing possibilities, the Pasteboard data item should include as many representations as possible.

The Clipboard reader must find the data type that best fits its capabilities, if any. Typically, this means selecting the most abundant available type. For example, a text editor might provide HTML (Rich text) and plain text representations of the copied data, an application that supports rich text should choose an HTML representation, and an application that supports only plain text should choose a plain text representation.

Change Count

The change count is a variable for each pasteboard, and it increments with each pasteboard's content-especially when adding, modifying, or removing data items. The application can changeCount determine whether the current data for the pasteboard is the same as the last data obtained by examining the change count (through attributes). Each time the change count is incremented, the pasteboard sends an advertisement to the observer who is interested in it.

Selection and Menu Management

Before you copy or cut some content in a view, you must first select some content. It may be some text, an image, a URL, a color, or other type of data, including custom objects . In order to implement copy-and-paste behavior in a custom view, you must manage the selection of objects in that view yourself. If a user selects an object in a view through a specific touch gesture (such as a double-click), you must handle the event, which is to record the selection within the program (while canceling the previous selection) and possibly indicate the new selection in the view. If a user can select multiple objects in the view and then make a copy-cut-paste operation, you must implement the multi-select behavior.

Note: touch events and their handling techniques are discussed in the "Touch Events" section.

When the application determines that the user has requested an Edit menu-it may be an action of choice-you should perform the following steps to display the menu:

    1. Call UIMenuController the sharedMenuController class method to get the global , that is, the menu controller instance.

    2. Computes the bounds of the selection and invokes the method with the resulting bounding rectangle setTargetRect:inView: . The Edit menu is displayed above or below the rectangle based on the distance between the selection and the top and bottom of the screen.

    3. Invokes a setMenuVisible:animated: method (two parameters are passed YES in) to animate the Edit menu above or below the selection.

Listing 3-4 shows how to display the touchesEnded:withEvent: Edit menu in the implementation of the method (note that the code that handles the selection is omitted from the example). In this code snippet, the custom view also sends a message to itself to becomeFirstResponder ensure that it is the first responder in the subsequent copy, cut, and paste operations.

Program Manifest 3-4 display the Edit 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 initial menu contains all the commands, so the first responder provides an implementation of the corresponding UIResponderStandardEditActions method ( copy: , paste: etc.). However, the system sends a message to the first responder before the menu is displayed canPerformAction:withSender: . In many cases, the first responder is the custom view itself. In the implementation of this method, the responder examines whether a given command (represented by the selector passed in by the first parameter) is appropriate for the current context. For example, if the selector is paste: , and there is no data on the pasteboard that the view can handle, the responder should return NO so that the paste command is forbidden. If the first responder does not implement the canPerformAction:withSender: method, or does not process the given command, the message enters the responder chain.

Program Listing 3-5 shows canPerformAction:withSender: an implementation of the method. The implementation first looks for copy: copy: paste: messages that match the,, and selectors, and activates or disables the copy, Cut, and paste menu commands based on the context of the current selection. For the Paste command, the contents of the pasteboard are also considered.

Program Manifest 3-5 conditionally activates 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);
        RetValue = [Super Canperformaction:action Withsender:sender];
    return retvalue;

Note that the last clause of this method else invokes the implementation of the superclass, giving the superclass a chance to handle commands that the subclass ignores.

Also note that manipulating a menu command may change the context of other menu commands. For example, when a user selects all objects in a view, the copy and cut commands should be included in the menu. In this case, although the menu is still visible, the responder can invoke the menu controller's update method so that the first responder canPerformAction:withSender: is called again.

Copy and cut the selected content

When the user touches the copy or Cut command on the Edit menu, the system invokes the responder object's copy: or method, respectively cut: . Typically, the first responder-that is, your custom view-implements these methods, but if not implemented, the message enters the responder chain as normal. Please note that UIResponderStandardEditActions These methods are declared in the informal agreement .

Note: because UIResponderStandardEditActions it is an informal protocol, any class in the application can implement its methods. However, the classes that implement these methods should inherit from the UIResponder class and should be installed in the responder chain in order for the commands to be passed by default on the responder chain.

In copy: the cut: response code of the or message, you need to write the object or data corresponding to the selection in as many representations as possible to the pasteboard. This operation involves the following steps (assuming only one of the pasteboard data items):

  1. Identifies or obtains the object or binary data corresponding to the selection.

    The binary data must be encapsulated in the NSData object . Other objects that can be written to the pasteboard must be property list objects-that is, the objects of these classes must be:,,,, NSString NSArray NSDictionary NSDate NSNumber , or NSURL (for more information about property list objects, see Property List Programming Guide ).

  2. If possible, generate one or more other representations for the object or data.

    For example, in the steps mentioned earlier to create an object for a selected image UIImage , you can UIImageJPEGRepresentation UIImagePNGRepresentation convert the image to a different representation by or function.

  3. Gets the Pasteboard object.

    In many cases, it is possible to use a universal pasteboard. You can use generalPasteboard the class method to get the object.

  4. Assigns an appropriate UTI to each data representation written to the Pasteboard data item.

    For a discussion of this topic, see the "Pasteboard Concept" section.

  5. Writes data for each representation type to the first Pasteboard data item:

    • Send a message to the Pasteboard object setData:forPasteboardType: to write to the data object.

    • Sending a message to the Pasteboard object setValue:forPasteboardType: can be written to the property list object.

  6. For the Cut ( cut: method) command, you need to remove the object represented by the selection from the application's data Model and update the view.

Program Listing 3-6 shows copy: cut: an implementation of the and method. cut:method invokes the copy: method, and then removes the selected object from the view and data model. Note that the copy: method archives the custom object in order to get an NSData object that is passed as a parameter to the Clipboard setData:forPasteboardType: method.

program manifest 3-6 copy and cut 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];
Paste Selection

The system invokes the method of the responder object when the user touches the Paste command on the Edit menu paste: . Typically, the first responder-that is, your custom view-implements these methods, but if not implemented, the message enters the responder chain as normal. paste:method in UIResponderStandardEditActions stated in the informal agreement .

In paste:   Message Response code, you can read the application-supported representations from the Pasteboard, and then add the pasted object to the application's data Model and displays the new object at the user-specified view location. This operation involves the following steps (assuming only a single pasteboard data item):

    1. Gets the Pasteboard object.

      In many cases, you can use the universal pasteboard, which you can do with generalpasteboard to obtain the object.

    2. Confirms that the first Pasteboard data item contains a representation that the application can handle, either by calling the Containspasteboardtypes: method, or by calling the Pasteboardtypes the method and examines its returned array of types to be implemented.

      Note that you should have performed this step in the implementation of the Canperformaction:withsender: method.

    3. If the first data item of the pasteboard contains data that the application can process, you can call the following method to read:

      • dataforpasteboardtype: , If the data to be read is encapsulated as NSData object , you can use this method.

      • valueforpasteboardtype: If the data to be read is encapsulated as property list object, use this method (see the" Copy and cut selected content "section).

    4. Joins the object into the application's data model.

    5. Displays the representation of an object in a user-specified location in the user interface.

Listing 3-7 is an implementation instance of the method that paste: performs the cut: copy: opposite of the method. The view in the example first verifies that the pasteboard contains custom presentation data that it supports, and if so, reads the data and joins it into the application's data model, and then identifies the part of the view-the current selection-as requiring redrawing.

program Manifest 3-7 paste the Clipboard data into the selected location

-(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];
Remove Edit Menu

The cut: copy: paste: Edit menu is automatically hidden when you implement, or when the command returns. Keep it visible by using the following code:

[Uimenucontroller setmenucontroller].menuvisible = YES;

The system may hide the Edit menu at any time, such as when a warning message is displayed or when the user touches another area of the screen, the Edit menu is hidden. If you have some status or screen display that depends on whether the Edit menu is displayed, you should listen UIMenuControllerWillHideMenuNotification to the announcement and perform the appropriate action.

Original address:

IOS copy, cut and paste theory basics (RPM)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.