Read from and write to clipboard

Hello,

To implement a “clipboard converter application” (no interface), I’m using this shameful ease to convert a text copied into the clipboard to uppercase:

NSText *theText =[[NSText alloc]init];
[theText selectAll:self];
[theText paste:self];
NSString *theString = [NSString stringWithString: [theText string]];
theString = [theString uppercaseString];
[theText setString:theString];
[theText selectAll:self];
[theText copy:self];

I’m sure there is a much more elegant way to do it using only NSPasteboard and NSString, but I get no results. Could you help me?

Honestly I don’t know what you are trying to do, but here’s a simple example of how to copy stuff in the Pasteboard:

NSData* dataToCopyToClipboard = [[NSString stringWithString:@"Example"] autorelease];
    [[NSPasteboard generalPasteboard] declareTypes:[NSArray arrayWithObjects:NSPasteboardTypeString, nil] owner:self];
    [[NSPasteboard generalPasteboard] setData:dataToCopyToClipboard forType:NSPasteboardTypeString];

Check the docs for NSPasteboard Class Reference. You have some options for reading from the pasteboard also.

This should point you in the right direction…

BTW, I never got this to work properly in ASOC… didn’t spend a lot of time trying, but works fine in cocoa, so I just let go… :slight_smile:

What is “clipboard converter application” supposed to do?

Hello leonsimard,

Thanks but this gives:

Calling -setData:forType: on NSPasteboard or NSPasteboardItem with object of type __NSCFConstantString instead of NSData.

I’m working with ARC (so neither autorelease allowed, nor implicit conversions).

Well, maybe I should let NSText do the job for me :slight_smile:

@ Ric,

“application” is a bit overdone term for a little accessory which takes a text copied into a text processor and allows to re-paste it at the same place after converting the text to upper string.

  1. Copy text
  2. Launch Uppercase.app, which terminates after conversion
  3. Paste text

I need the è,à ,é,ù. to be converted into accentuated equivalents.

Try this:


	    NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
	    NSArray *classArray = [NSArray arrayWithObject:[NSString class]];
	    NSDictionary *options = [NSDictionary dictionary];
	    BOOL ok = [pasteboard canReadObjectForClasses:classArray options:options];
	    if (ok) {
	        NSArray *objectsToPaste = [pasteboard readObjectsForClasses:classArray options:options];
	        NSString *text = [objectsToPaste objectAtIndex:0];
			text = [text uppercaseString];
	        [pasteboard clearContents];
	        NSArray *array = [NSArray arrayWithObject:text];
	        [pasteboard writeObjects:array];
	    }

For full usefulness, you should modify it to handle RTF too.