TweetFollow Us on Twitter

The Road to Code: The Glue That Binds

Volume Number: 25
Issue Number: 09
Column Tag: Road to Code

The Road to Code: The Glue That Binds

Copy and paste

by Dave Dribin

One of the hallmark features of modern GUI applications is the ability to copy content and paste it into either the same or a second, separate application. In this month's article, we are going to add copy and paste to the Favorite Word application that we developed in the June 2009 article. As a quick refresher, our application has a single window with a custom view that displays your favorite word, as shown in Figure 1.


Figure 1: Favorite Word window

The word can currently only be set in the application's preferences. We're going to add the ability to copy, cut, and paste the word in the custom view. In addition, if the user pastes a word, we're going to update the word in the preferences.

It turns out that our application already has an Edit menu along with the Cut, Copy, and Paste menu items, since they're included with the standard application template. However, if you open the Edit menu, you'll notice that all three are grayed out, as shown in Figure 2.


Figure 2: Disabled Cut, Copy, and Paste

Before we delve into the code changes needed to bring copy, cut, and paste to our application, we need to cover the first responder, the responder chain, and nil-targeted actions topics.

Responders

In the April article, A Window with a View, we talked about the view hierarchy and the NSResponder class. As a quick overview, the view hierarchy is how views (subclasses of NSView) are arranged inside a window. For example, the window in Figure 3 has a view hierarchy as shown in Figure 4.


Figure 3: Window with text field and button


Figure 4: View hierarchy

Also, the NSResponder class is the base class for all classes that participate in the Cocoa event handling system, and the NSView class is a subclass of NSResponder. This makes all views capable of handling events. In the April article, you learned how to handle mouse events by overriding the mouseDown:, mouseUp:, and mouseDragged: methods of NSResponder.

First Responder

Even though windows contain multiple views, keyboard events are only routed to one view that has the users focus. This focused view is designated as the first responder. The first responder is the first view that is given the opportunity to handle user events. It doesn't have to handle events, but it has the first opportunity to do so. As the user clicks or tabs around to other views in the window, the first responder changes.

The way the first responder changes is a bit complicated, because the current first responder may refuse to give up its first responder status, or the view the user clicks on may reject first responder status.

Responder Chain

I mentioned above that the first responder gets first crack at handling keyboard events. If a view decides not to handle the event, the application keeps trying to find a responder that does handle the event. The application will next ask the first responder's super view to handle the event. If this view does not handle the event, it continues up the view hierarchy. If none of the views handle the event, the NSWindow gets a chance to handle the event, and finally an NSWindowController, if there is one.

Nil-Targeted Actions

In some case, the responder chain is also used for handling actions. In previous articles, we've used a specific target and selector to handle actions. For example, when we connect up a button's action in Interface Builder by control-dragging to our controller class, it sets the target and selector of the button's action. If we were to emulate this in code, it would look like:

    [button setTarget:controller];
    [button setAction:@selector(buttonPressed:)];

This tells the button selector, in this case buttonPressed:, to call on a specific object, controller. However, the target does not need to be a specific object. It can be set to nil which has special meaning: to call the action selector on the first responder. If the first responder does not implement the action selector, then the application tries to find some object to which to send the action. To do this, it uses the responder chain in a similar manner to what I described above for handling key events. The precise nature of the responder chain for nil-targeted actions is a bit complicated, so for the exact rules, I suggest you read the Cocoa Event-Handling Guide on the Apple's developer site. The important point to note is that the first responder gets to handle nil-target events.

Handling Copy, Cut, and Paste Actions

So how does all this fit into copy, cut, and paste? As it turns out the Copy, Cut, and Paste menu items are not disabled because they are not connected up to anything. They are actually connected to an action selector, but they are nil-targeted actions. The copy, cut, and paste menu items are connected to the following action selectors, respectively:

- (IBAction)copy:(id)sender;
- (IBAction)cut:(id)sender;
- (IBAction)paste:(id)sender;

The reason why the menu items are grayed out is because neither the first responder nor any object in the responder chain implements these methods. To fix this, we need make sure our custom view, WordView, becomes first responder and then implement these methods.

NSView has a method named acceptsFirstResponder that returns a BOOL:

- (BOOL)acceptsFirstResponder;

The default implementation of this method returns NO, meaning it cannot become the first responder. Since our view currently cannot become the first responder, it does not become part of the responder chain, and thus is not eligible to handle the copy, cut, and paste action methods. Thus, our first step is to override this method to return YES in WordView.m:

- (BOOL)acceptsFirstResponder
{
    return YES;
}

Next, we need to implement the action methods, but let's just use stubs for now, just to make sure we've got everything hooked up right:

- (IBAction)copy:(id)sender
{
    NSLog(@"Copy");
}
- (IBAction)cut:(id)sender
{
    NSLog(@"Cut");
}
- (IBAction)paste:(id)sender
{
    NSLog(@"Paste");
}

If you run the application at this point, the Cut, Copy, and Paste menu items should be selectable, and if you chose one, you should see the appropriate log message.

How did that happen? Since our custom view is the only view in the window, the window is going to ask it if it wants to become the first responder. Since the view accepts first responder status, it becomes the first responder. When the user clicks the Edit menu, the application checks the responder chain for an object to handle the cut:, copy:, and paste: action methods. Since our custom view does, and it's the first responder, the application knows it can send these actions to our view and makes the menu items available. When the user actually selects, for example, the Copy menu item, the application sends the action to our view.

The Pasteboard

We've got the user interface working properly, but now we actually need to implement the action methods. Copy and paste between applications is handled by the pasteboard. The pasteboard lives outside of all applications and acts as a mediator between them to support copy and paste. When a user copies some text, the source application puts this text on the pasteboard. When the user pastes in another application, the receiving application retrieves the text from the pasteboard.

Cocoa has a class called NSPasteboard that provides an interface to the pasteboard. It handles the low-level inter-process communication and makes implementing copy and paste relatively straightforward.

To implement copy, an application puts data on the pasteboard. An application may put multiple representations of the data on the pasteboard. For example, an application may put styled text as RTF or PDF as well as plain text on the pasteboard. The application that receives data from the pasteboard can choose the best representation for its needs. For example, TextEdit may choose the styled text whereas Terminal may choose the plain text.

Putting Data on the Pasteboard

To put data on the pasteboard, you first need an instance of the NSPasteboard class. Then you tell it what types of data you are going to put on the pasteboard. And finally, you put the actual data for each type on the pasteboard. Here's code to put a string on the pasteboard:

    NSString * string = @"a string";
    NSPasteboard * pasteboard = [NSPasteboard  generalPasteboard];
    NSArray * types = [NSArray  arrayWithObject:NSStringPboardType];
    [pasteboard declareTypes:types owner:nil];
    [pasteboard setString:string forType:NSStringPboardType];

While we are using a static string, the string variable would come from the view, as we shall soon see. There are multiple different pasteboards in the system, but the general pasteboard is used for copy and paste. You can get a reference to the general pasteboard by using the +generalPasteboard class method. The declareTypes:owner: method tells the pasteboard which types of data you are going to put on the pasteboard. You pass it an array of types, ordered by preference of type, with the preferred type first. The NSStringPboardType is a constant for plain text type. If an application uses rich text and plain text, it probably wants to use the rich text first. Since this example uses only plain text, that's all we need. Finally, we put the plain text on the pasteboard using the setString:forType: method.

When an application declares the types it's going to put on the pasteboard, it gives the pasteboard an owner. This is because it may not want to put the actual data on the pasteboard immediately. Say an application wants to put an image on the pasteboard in multiple formats. It's rather wasteful to put all image types on the pasteboard immediately. In these cases, the source application may put a promise on the pasteboard. When and if another application requests the data from the pasteboard, the pasteboard will ask the owner to provide the data and fulfill the promise. Since we are providing all the data immediately, we do not have to set the owner.

Reading Data from the Pasteboard

Just as the sending application may put multiple types of data on the pasteboard, the receiving application may accept multiple types. Again, the application specifies which types it can support, and then, if the pasteboard contains any of those types, it retrieves the data. The code to retrieve a string from the pasteboard looks like this:

    NSPasteboard * pasteboard = [NSPasteboard generalPasteboard];
    NSArray * types = [NSArray arrayWithObject:NSStringPboardType];
    NSString * bestType = [pasteboard availableTypeFromArray:types];
    if (bestType != nil)
    {
        NSString * value =
            [pasteboard stringForType:NSStringPboardType];
        // Use pasted value
    }

Again, this code uses the general pasteboard. The availableTypeFromArray: returns the best type of all those specified in the array or nil if none of the types are available. Finally, the stringForType: method retrieves the actual string from the pasteboard.

Implementing Copy

Armed with our new knowledge of the pasteboard, we can now implement copy for our WordView custom view. Since this view uses styled text to draw the string using an attributed string, it can put both styled text and plain text on the pasteboard. It's easy to get an RTF representation of an attributed string, so we can use RTF as the styled text type.

As a refresher, here is the drawRect: method that creates an attributed string:

- (void)drawWord
{
    NSRect bounds = [self bounds];
    bounds = NSInsetRect(bounds, 4.0, 4.0);
    
    NSFont * font = [NSFont systemFontOfSize:50];
    NSDictionary * attributes =
        [NSDictionary dictionaryWithObject:font
                                    forKey:NSFontAttributeName];
    NSAttributedString * string = 
        [[NSAttributedString alloc] initWithString:_word
                                        attributes:attributes];
    
    NSSize stringSize = [string size];
    NSPoint point;
    // Center vertically
    point.y = bounds.size.height/2 - stringSize.height/2;
    
    // Align horizonally
    if (_textAlignment == WordViewCenterTextAlignment)
        point.x = bounds.size.width/2 - stringSize.width/2;
    else if (_textAlignment == WordViewLeftTextAlignment)
        point.x = bounds.origin.x;
    else if (_textAlignment == WordViewRightTextAlignment)
        point.x = bounds.size.width - stringSize.width;
    
    [string drawAtPoint:point];
}

We are creating an attributed string with a font size of 50 points. Since we can use the attributed string in our copy: method, we can re-use this code by extracting t into its own method. Extracting code into a method is one of the refactoring types that Xcode supports, so let's use it to help us out.

To do this, you select the code you want to extract, as shown in Figure 5, and then choose the Edit > Refactor... menu. Xcode then analyzes the code and pops up a dialog box to name this new method. Name it wordAsAttributedString, and then chose Preview followed by Apply.


Figure 5: Selection to extract

Xcode creates the method and calls it where your selection was. I typically fix up the indentation and coding style a bit, but this refactoring tool does help automate creating a new method from existing code. In the end, this new method should look like this:

- (NSAttributedString *)wordAsAttributedString
{
    NSFont * font = [NSFont systemFontOfSize:50];
    NSDictionary * attributes =
    [NSDictionary dictionaryWithObject:font
                                forKey:NSFontAttributeName];
    NSAttributedString * string = 
        [[NSAttributedString alloc] initWithString:_word
                                        attributes:attributes];
    return string;
}

We can now write a method that puts the word on the pasteboard, in both rich text and plain text:

- (void)writeToPasteboard:(NSPasteboard *)pasteboard
{
    NSArray * types = [NSArray arrayWithObjects:
                       NSRTFPboardType, NSStringPboardType,  nil];
    [pasteboard declareTypes:types owner:nil];
    
    [pasteboard setString:_word forType:NSStringPboardType];
    
    NSAttributedString * attributedWord = [self  wordAsAttributedString];
    NSRange fullRange = NSMakeRange(0, [attributedWord  length]);
    NSData * rtfData = [attributedWord RTFFromRange:fullRange 
                                 documentAttributes:nil];
    [pasteboard setData:rtfData forType:NSRTFPboardType];
}

This code is similar to the simple case we looked at above for writing a plain text string. In this case, the pasteboard is being passed in, to make this code more generic. It is also declaring two types, an RTF type and a plain text string type. Setting the string data is simple enough, since we can use the _word instance variable. Setting the RTF data is a bit more involved because we have to specify the range of characters. We create a range that encompasses the full string. And finally, it sets the RTF data using the setData:forType: method.

All we have left to do is to call this method from the copy: method:

- (IBAction)copy:(id)sender
{
    NSPasteboard * pasteboard = [NSPasteboard  generalPasteboard];
    [self writeToPasteboard:pasteboard];
}

With this code in place, we can now finally test out copy. Run the application and chose the Edit > Copy menu item. Now run TextEdit and chose Edit > Paste in a new document. The TextEdit document should contain the word "Cocoa" with in same font and size that we used in our application, as shown in Figure 6.


Figure 6: Pasted RTF

If you try pasting in a plain text document or an application like the Terminal, then only the word "Cocoa" is pasted, without the font style. This is because our application put both rich and plain text on the pasteboard.

Implementing Paste

With copy implemented, we now need to implement paste. In a similar fashion, we are going to use a generic method to read from a pasteboard, as follows:

- (BOOL)readFromPasteboard:(NSPasteboard *)pasteboard
{
    NSArray * supportedTypes =
        [NSArray arrayWithObject:NSStringPboardType];
    NSString * bestType =
        [pasteboard availableTypeFromArray:supportedTypes];
    if (bestType == nil)
        return NO;
    
    NSString * value =
        [pasteboard stringForType:NSStringPboardType];
    NSCharacterSet * whitespace =
        [NSCharacterSet whitespaceCharacterSet];
    value = [value stringByTrimmingCharactersInSet:whitespace];
    NSArray * words =
        [value componentsSeparatedByCharactersInSet:whitespace];
    if ([words count] != 1)
        return NO;
    
    self.word = value;
    return YES;
}

To simplify matters, we are only going to accept plain text type. This method returns a BOOL that returns YES if it did update the word from the pasteboard, otherwise NO. Since our view is only supposed to show a single word, it also ensures that there's only one word on the pasteboard.

This code retrieves a plain text string from the pasteboard, as previously demonstrated, returning NO if the plain text type is not available. Next, we need to count the number of words in this string. First, we use the stringByTrimmingCharactersInSet: method to remove leading and trailing whitespace characters. The whitespace character set includes the space and tab characters. After removing any leading and trailing whitespace, we split the string into words by using componentsSeparatedByCharactersInSet:. If the number of words is not one, then we abort and return NO. If there is a single word, we set our word to this new word and return YES.

To complete our paste implementation, we need to implement the paste: method as follows:

- (IBAction)paste:(id)sender
{
    NSPasteboard * pasteboard = [NSPasteboard generalPasteboard];
    if (![self readFromPasteboard:pasteboard])
        NSBeep();
}

Again, we use the general pasteboard. If reading from the pasteboard fails, we beep to let the user know something has gone wrong.

Implementing Cut

Cut is similar to a copy followed by a delete action. Thus we could implement cut: as follows:

- (IBAction)cut:(id)sender
{
    [self copy:sender];
    self.word = @"";
}

Updating User Preferences

We've now finished updating our WordView. The application stores the user's favorite word in its preferences. As a final touch, we'd like to update the user preferences when the user pastes in a new word. Since the view is supposed to be a generic word view, we don't want to put this logic in the view. Thus, the main window controller needs to watch for changes to the view's word and update the preferences. Thankfully, our view is fully key-value coding (KVC) compliant, so we can use key-value observing (KVO) to be notified of changes to the word. At the end of the awakeFromNib method add this bit of code:

    [_wordView addObserver:self
                forKeyPath:@"word"
                   options:0
                   context:&WordChangedContext];

In the observer method, we want to update the user defaults:

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if (context == &WordChangedContext)
    {
        NSUserDefaults * defaults =
            [NSUserDefaults standardUserDefaults];
        [defaults setObject:_wordView.word
                     forKey:FavoriteWordKey];
    }
}

Unfortunately, this code has a serious bug. The main window controller is already observing changes to user defaults and updates the word view if it changes. The code as it stands results in an infinite loop. Updating the default value sets the word view's word, which again triggers the key-value observing method. This in turn sets the default again, ad infinitum.

To fix this, we don't want to update the word view's word if the default changed due to a KVO trigger. We use a new instance variable, _wordUpdatingFromView that is set to YES during our KVO method:

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if (context == &WordChangedContext)
    {
        _wordUpdatingFromView = YES;
        NSUserDefaults * defaults =
            [NSUserDefaults standardUserDefaults];
        [defaults setObject:_wordView.word
                     forKey:FavoriteWordKey];
        _wordUpdatingFromView = NO;
    }
}

Finally, we need to update our notification method to use this new instance variable, as well:

- (void)updateFromDefaults:(NSNotification *)notification
{
    NSUserDefaults * defaults =
        [NSUserDefaults standardUserDefaults];
    if (!_wordUpdatingFromView)
        _wordView.word = [defaults objectForKey:FavoriteWordKey];
    
    NSData * colorData = [defaults objectForKey:BackgroundColorKey];
    NSColor * color =
        [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
    _wordView.backgroundColor = color;
    
    WordViewTextAlignment alignment =
        [defaults integerForKey:TextAligmentKey];
    _wordView.textAlignment = alignment;
}

The only modification from our previous version is these two lines:

    if (!_wordUpdatingFromView)
        _wordView.word = [defaults objectForKey:FavoriteWordKey];

This protects from the infinite loop, only updating the word view if it wasn't initiated from the word view itself.

Conclusion

In this article, we've learned all about the first responder, the responder chain, nil-target actions, and also the pasteboard. And we've put all of these concepts together so we could implement copy, paste, and cut. As usual, the full code is available on the MacTech website.


Dave Dribin has been writing professional software for over eleven years. After five years programming embedded C in the telecom industry and a brief stint riding the Internet bubble, he decided to venture out on his own. Since 2001, he has been providing independent consulting services, and in 2006, he founded Bit Maki, Inc. Find out more at http://www.bitmaki.com/ and http://www.dribin.org/dave/.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.