Snippet #39
Language: Objective-C++, Author: Octomagon (www.baconday.org/apps)
License: Public domain
Add/Remove your app from Login Items
These are two methods to add and remove your program from the Login Items list in Mac OS X 10.4.
I didn't write most of the code. It Originally came from http://www.cocoadev.com/index.pl?StartingMyAppOnStartup
I split the original code into 2 methods and made it automatically detect the name of your app.
-You don't have to modify anything to add these to your app. Just drop them into your code.
-OS X keeps the addToLoginItems method from adding your app twice. (sweet!)
-You don't have to check if your app is already listed. The removeFromLoginItems method does it for you.
-This, to me, seem MUCH easier than using Apple's LoginItemsAE class.
- (void)removeFromLoginItems { NSString *appName = [[[NSBundle mainBundle] bundlePath] lastPathComponent]; NSString *loginWindowPlistPath = [@"~/Library/Preferences/loginwindow.plist" stringByExpandingTildeInPath]; NSMutableDictionary *loginWindowPrefsDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:loginWindowPlistPath]; NSMutableArray *launchItems = [NSMutableArray arrayWithArray:[loginWindowPrefsDictionary valueForKey:@"AutoLaunchedApplicationDictionary"]]; NSEnumerator *enumerator = [launchItems objectEnumerator]; id application; while ( application = [enumerator nextObject] ) { if ( [[[application valueForKey:@"Path"] lastPathComponent] isEqualToString: appName] ) { // These 4 lines are run if the app is found in "Login Items". // You can replace these lines with something like "return YES;" // if you just want a method that checks for your app in the list. [launchItems removeObject:application]; [loginWindowPrefsDictionary setObject:launchItems forKey:@"AutoLaunchedApplicationDictionary"]; [loginWindowPrefsDictionary writeToFile:loginWindowPlistPath atomically:YES]; return; } } } - (void)addToLoginItems { NSString *fullPath = [[NSBundle mainBundle] bundlePath]; NSString *script = [NSString stringWithFormat:@"set appPath to \"%@\" \ntell application \"System Events\" \nmake login item at end with properties {path:appPath, hidden:false} \nend tell", fullPath]; NSAppleScript *appleScript = [[NSAppleScript alloc] initWithSource:script]; [appleScript executeAndReturnError:nil]; }
Compatible with:
- Mac OS X 10.4 PPC
- Mac OS X 10.4 Intel
- Mac OS X 10.5 PPC
- Mac OS X 10.5 Intel

In the method addToLoginItems, a 'release' is never sent to NSAppleScript *appleScript after it's allocated. Seems like a memory leak?