Pasteboard notification

Discussion in 'Mac Programming' started by mathcolo, Apr 4, 2009.

  1. macrumors 6502a

    mathcolo

    Joined:
    Sep 14, 2008
    Location:
    Massachusetts
    #1
    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!
     
  2. Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    AFAIK, you have to poll the pasteboard for changes. I don't think there's any sort of event/notification sent when it changes.
     
  3. thread starter macrumors 6502a

    mathcolo

    Joined:
    Sep 14, 2008
    Location:
    Massachusetts
    #3
    Wouldn't that use a lot of CPU?
     
  4. Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #4
    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;
    }
     

Share This Page