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

Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »

Price Scanner via MacPrices.net

New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more

Jobs Board

DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.