cocoa snippets

RubyCocoa HelloWorld

Tagged rubycocoa, osx, helloworld, cocoa  Languages ruby
require 'osx/cocoa'; include OSX 
app = NSApplication.sharedApplication 

win = NSWindow.alloc.initWithContentRect_styleMask_backing_defer( 
    [0, 0, 200, 60], 

win.title = 'Hello World' 
button = NSButton.alloc.initWithFrame(NSZeroRect) 

button.bezelStyle = NSRoundedBezelStyle 
button.title = 'Hello!' 
button.frameOrigin = NSMakePoint((win.contentView.frameSize.width / 2.0) - (button.frameSize.width / 2.0), 
                                 (win.contentView.frameSize.height / 2.0) - (button.frameSize.height / 2.0)) 
button_controller = 
def button_controller.sayHello(sender) 
  puts "Hello World!" 
end = button_controller 
button.action = 'sayHello:' 


How to scroll images with NSImageView and NSScrollView

Tagged scroll, cocoa, objective-c, autoresize, nsscrollview, nsimageview  Languages objectivec
  1. In IB (Interface Builder) add an NSImageView to the window.
  2. Select the NSImageView.
  3. From the menu select Select Layout ~~> Embed Objects In~~> Scroll View.
  4. Select the NSScrollView press Cmd+3 and configure the NSScrollView to expand and fill all available space.
  5. Remove the NSImageView's border
  6. Use this code to resize the NSImageView's frame to match the size of the NSImage
NSImageView *imageView = ...;
[imageView setFrameSize:viewSize];

NSLog(@"imageView's frame after resizing: %@", NSStringFromRect([imageView frame]));

Registering global hot keys with Cocoa and Objective-C

Tagged objective-c, cocoa, hotkeys  Languages objectivec

In your application's controller add the following:

- (void)awakeFromNib
    [self registerHotKeys];

And the following code which registers the hot keys:

    EventHotKeyRef gMyHotKeyRef;
    EventHotKeyID gMyHotKeyID;
    EventTypeSpec eventType;
    InstallApplicationEventHandler(&OnHotKeyEvent, 1, &eventType, (void *)self, NULL);
    RegisterEventHotKey(20, cmdKey+optionKey, gMyHotKeyID, GetApplicationEventTarget(), 0, &gMyHotKeyRef);  
    RegisterEventHotKey(21, cmdKey+optionKey, gMyHotKeyID, GetApplicationEventTarget(), 0, &gMyHotKeyRef);  
    RegisterEventHotKey(23, cmdKey+optionKey, gMyHotKeyID, GetApplicationEventTarget(), 0, &gMyHotKeyRef);  

OSStatus OnHotKeyEvent(EventHandlerCallRef nextHandler,EventRef theEvent,void *userData)
    EventHotKeyID hkCom;
    GetEventParameter(theEvent, kEventParamDirectObject, typeEventHotKeyID, NULL, sizeof(hkCom), NULL, &hkCom);
    AppController *controller = (AppController *)userData;  
    int l =;
    switch (l) {
        case 1:         
            NSLog(@"Capture area"); 
            [ScreenCapture captureArea:controller];
        case 2: 
            NSLog(@"Capture screen");   
            [ScreenCapture captureScreen:controller];
        case 3: 
            NSLog(@"Capture window");   
            [ScreenCapture captureWindow:controller];

    return noErr;

The code used in this snippet was inspired by this blog post


If you need a more complete solution you can use one of these open-source alternatives:

Showing the application window

Usually you want to show the application window when the hot key is pressed. This can be done as explained in this snippet

How to create an icon for your Cocoa application

Tagged icon, cocoa  Languages 
  1. Create a 512x512 pixel icon with Photoshop and save it as a PSD file
  2. Open the Icon Composer app and drag the PSD file into the first slot
  3. Choose Save as from the menu
  4. Import the file into XCode
  5. Open Info.plist and set the Icon File setting to the file you just imported
  6. Clean and recompile

How to make a clickable link inside a NSTextField and Cocoa

Tagged nstextfield, cocoa, clickable, url  Languages objectivec

From How do I embed a hyperlink inside an NSTextField or NSTextView?


#import <Cocoa/Cocoa.h>

@interface NSAttributedString (Hyperlink)
+(id)hyperlinkFromString:(NSString*)inString withURL:(NSURL*)aURL;


#import "NSAttributedString+Hyperlink.h"

@implementation NSAttributedString (Hyperlink)
+(id)hyperlinkFromString:(NSString*)inString withURL:(NSURL*)aURL
    NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString: inString];
    NSRange range = NSMakeRange(0, [attrString length]);
    [attrString beginEditing];
    [attrString addAttribute:NSLinkAttributeName value:[aURL absoluteString] range:range];
    // make the text appear in blue
    [attrString addAttribute:NSForegroundColorAttributeName value:[NSColor blueColor] range:range];
    // next make the text appear with an underline
    [attrString addAttribute:
     NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSSingleUnderlineStyle] range:range];
    [attrString endEditing];
    return [attrString autorelease];

This code sets the contents of the NSTextField to a URL:

#import "NSAttributedString+Hyperlink.h"

[textURL setAllowsEditingTextAttributes: YES];
[textURL setSelectable: YES];
NSURL* url = [NSURL URLWithString:@""];
NSMutableAttributedString* string = [[NSMutableAttributedString alloc] init];
[string appendAttributedString: [NSAttributedString hyperlinkFromString:@"Apple Computer" withURL:url]];
[textURL setAttributedStringValue: string];

How to set an application to load at login with Cocoa and Objective-C

Tagged cocoa, objective-c, startup, login  Languages objectivec

In XCode add the following to your controller's header file:

@interface AppController : NSObject {
IBOutlet NSButton *buttonOpenAtLogin;
- (IBAction)addLoginItem:(id)sender;
- (void)enableLoginItemWithLoginItemsReference:(LSSharedFileListRef )theLoginItemsRefs ForPath:(CFURLRef)thePath;
- (void)disableLoginItemWithLoginItemsReference:(LSSharedFileListRef )theLoginItemsRefs ForPath:(CFURLRef)thePath;

Add the following to the implementation:

@implementation AppController

- (void)enableLoginItemWithLoginItemsReference:(LSSharedFileListRef )theLoginItemsRefs ForPath:(CFURLRef)thePath {
    // We call LSSharedFileListInsertItemURL to insert the item at the bottom of Login Items list.
    LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(theLoginItemsRefs, kLSSharedFileListItemLast, NULL, NULL, thePath, NULL, NULL);        
    if (item)

- (void)disableLoginItemWithLoginItemsReference:(LSSharedFileListRef )theLoginItemsRefs ForPath:(CFURLRef)thePath {
    UInt32 seedValue;
    // We're going to grab the contents of the shared file list (LSSharedFileListItemRef objects)
    // and pop it in an array so we can iterate through it to find our item.
    NSArray  *loginItemsArray = (NSArray *)LSSharedFileListCopySnapshot(theLoginItemsRefs, &seedValue);
    for (id item in loginItemsArray) {      
        LSSharedFileListItemRef itemRef = (LSSharedFileListItemRef)item;
        if (LSSharedFileListItemResolve(itemRef, 0, (CFURLRef*) &thePath, NULL) == noErr) {
            if ([[(NSURL *)thePath path] hasPrefix:SGApplicationPath])
                LSSharedFileListItemRemove(theLoginItemsRefs, itemRef); // Deleting the item
    [loginItemsArray release];

- (IBAction)addLoginItem:(id)sender {
    CFURLRef url = (CFURLRef)[NSURL fileURLWithPath:SGApplicationPath];
    // Create a reference to the shared file list.
    LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
    if (loginItems) {
        if ([[buttonOpenAtLogin selectedCell] state] == YES)
            [self enableLoginItemWithLoginItemsReference:loginItems ForPath:url];
            [self disableLoginItemWithLoginItemsReference:loginItems ForPath:url];

In Interface Builder do the following:

  • Add a User Defaults Controller Bindings object to IB.
  • Add a checkbox button or menu item to IB
  • Bind the button to the IBOutlet in the controller
  • Select the button and bind it to the User Defaults Controller (Cmd+5). Enter values in "Controller Key" and "Model Key Path"

Code found here

See for more details...

How to capture photos/videos with iSight and Objective-C

Tagged objective-c, record, cocoa, isight  Languages objectivec

There are plenty of resources online that explain how to access iSight:

This article explains how to use QuartzComposer for capturing images with iSight. The benefit of using QuartzComposer is that you don't have to write a lot of code to capture an image. All you have to do is setup a QCView with IB and bind it to an outlet, then to get the snapshot you call this method:

NSImage *screenshot = [isightView snapshotImage];

Alternatively, you could also use:

- (id) createSnapshotImageOfType:(NSString*)type

The code in the article didn't work for me:

NSImage *currentImage = [qcView valueForOutputKey:@"ImageOutput"];

The article also forgot to mention that you have to import and link to the following frameworks:

#import <QuartzCore/QuartzCore.h>
#import <Quartz/Quartz.h>

Haven't tried this one yet.

This example is not complete.

Have a look at one of the demos like StillMotion

How to display a modal dialog with Objective-C and Cocoa

Tagged nsrunalertpanel, objective-c, cocoa, modal, dialog  Languages objectivec
int choice = NSRunAlertPanel(@"title", @"description", @"DEFAULT", @"ALTERNATE", "OTHER", 8);
if(choice == NSAlertDefaultReturn)        

} else if(choice == NSAlertOtherReturn) {

} else if(choice == NSAlertAlternateReturn) {