Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

mathcolo

macrumors 6502a
Original poster
Sep 14, 2008
860
16
Boston
For a Cocoa program that I'm developing, I'd like to have my program watch the pasteboard for new pastes and add a 1 to it. For example, the program would automatically do this:

I Paste Hello
The program makes it 1Hello

I've been looking at NSNotification and the shared notification center but I didn't find a notification for doing this. Any assistance would be greatly appreciated. Thanks!
 

kainjow

Moderator emeritus
Jun 15, 2000
7,958
7
AFAIK, you have to poll the pasteboard for changes. I don't think there's any sort of event/notification sent when it changes.
 

kainjow

Moderator emeritus
Jun 15, 2000
7,958
7
Nope, with this little test it only uses 0.02% running every 1/4th of a second:

Code:
#import <Cocoa/Cocoa.h>


@interface Watcher : NSObject {
	NSInteger lastChangeCount;
	NSPasteboard *pasteboard;
}
@end

@implementation Watcher
- (id)init {
	if (self = [super init]) {
		pasteboard = [[NSPasteboard generalPasteboard] retain];
		[NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(checkPasteboard:) userInfo:nil repeats:YES];
	}
	return self;
}

- (void)checkPasteboard:(NSTimer *)timer {
	NSInteger currentChangeCount = [pasteboard changeCount];
	if (currentChangeCount == lastChangeCount)
		return;
	NSLog(@"Pasteboard changed: %@", [pasteboard types]);
	lastChangeCount = currentChangeCount;
}
@end


int main (int argc, const char * argv[]) {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[[Watcher alloc] init];
	[[NSRunLoop currentRunLoop] run];
	[pool release];
	return 0;
}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.