Objective C AñadeuncÃrculorojo con un texto en blanco al icono delaaplicaciónenel dock

-(void) updateApplicationIcon:(int) theNumber:(NSRect) theRect{
	// get the current app icon
	NSImage *appImage = [NSImage imageNamed:@"NSApplicationIcon"];
	
	// create a new image and draw the app icon onto it
	NSImage *image = [[NSImage alloc] initWithSize:[appImage size]];
	
	// lock focus on the new image and draw the app icon onto it.
	// you'll want the image flipped so text shows up correctly
	[image setFlipped:TRUE];
	[image lockFocus];
	NSSize appSize = [appImage size];	
	[appImage compositeToPoint:NSMakePoint(0, appSize.height) 
					 operation:NSCompositeSourceOver];
	
	// draw red circle
	NSBezierPath *redCircle = [NSBezierPath bezierPathWithOvalInRect:NSMakeRect(8,43,45,45)];
	[[NSColor redColor] setFill];
	[redCircle fill];
	
	// draw whatever else you want onto the image
	NSArray *values = [NSArray arrayWithObjects:[NSColor whiteColor], [NSFont fontWithName:@"Tahoma" size:32], nil];
	NSArray *keys = [NSArray arrayWithObjects:NSForegroundColorAttributeName, NSFontAttributeName, nil];
	
	NSDictionary *attrs = [NSDictionary dictionaryWithObjects:values forKeys:keys];
	NSString *caption= [NSString stringWithFormat:@"%d", theNumber];
	NSAttributedString *text= [[NSAttributedString alloc] initWithString:caption attributes:attrs];
	[text drawInRect:theRect];
	
	// unlock focus and set the new image as the dock icon
	[image unlockFocus];
	[NSApp setApplicationIconImage:image];
}

Objective C Limpiar el icono delaaplicaciónenel dock

-(void) initApplicationIcon{
	// empty application icon
	NSImage *appImage = [NSImage imageNamed:@"NSApplicationIcon"];
	[NSApp setApplicationIconImage:appImage];
}

Objective C 单击窗口时如何防止应用程序变为活动状态?

- (BOOL)canBecomeKeyWindow;
- (BOOL)canBecomeMainWindow;
- (BOOL)acceptsFirstResponder;

of NSView:


- (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)theEvent;

and the style mask during the initialization:


styleMask:(� your app specific other flags� | NSNonactivatingPanelMask)

Objective C 比较两个版本字符串

/*
 * compareVersions(@"10.4",             @"10.3")             returns NSOrderedDescending (1)
 * compareVersions(@"10.5",             @"10.5.0")           returns NSOrderedSame (0)
 * compareVersions(@"10.4 Build 8L127", @"10.4 Build 8P135") returns NSOrderedAscending (-1)
 */
NSComparisonResult compareVersions(NSString* leftVersion, NSString* rightVersion)
{
	int i;
		
	// Break version into fields (separated by '.')
	NSMutableArray *leftFields  = [[NSMutableArray alloc] initWithArray:[leftVersion  componentsSeparatedByString:@"."]];
	NSMutableArray *rightFields = [[NSMutableArray alloc] initWithArray:[rightVersion componentsSeparatedByString:@"."]];
	
	// Implict ".0" in case version doesn't have the same number of '.'
	if ([leftFields count] < [rightFields count]) {
		while ([leftFields count] != [rightFields count]) {
			[leftFields addObject:@"0"];
		}
	} else if ([leftFields count] > [rightFields count]) {
		while ([leftFields count] != [rightFields count]) {
			[rightFields addObject:@"0"];
		}
	}
	
	// Do a numeric comparison on each field
	for(i = 0; i < [leftFields count]; i++) {
		NSComparisonResult result = [[leftFields objectAtIndex:i] compare:[rightFields objectAtIndex:i] options:NSNumericSearch];
		if (result != NSOrderedSame) {
			[leftFields release];
			[rightFields release];
			return result;
		}
	}
	
	[leftFields release];
	[rightFields release];	
	return NSOrderedSame;
}

Objective C 处理无效的UTF-8

// http://www.omnigroup.com/ftp/pub/software/Source/MacOSX/Frameworks/
// Link with {OWF, OmniFoundation, OmniBase, OmniNetworking}
// http://forums.omnigroup.com/showthread.php?t=1867
#import <OWF/OWDataStream.h>
#import <OWF/OWDataStreamCharacterCursor.h>

NSString* stringWithUTF8Data(NSData *data)
{
	OWDataStream *dataStream = [[[OWDataStream alloc] initWithLength:[data length]] autorelease];
	[dataStream writeData:data];
	return OFMostlyApplyDeferredEncoding([[[[OWDataStreamCharacterCursor alloc] initForDataCursor:[dataStream newCursor] encoding:OFDeferredASCIISupersetStringEncoding] autorelease] readString], kCFStringEncodingUTF8);
}

Objective C 将东西安装到/ usr / bin - Trampolines

int main(int argc, char *argv[])
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSWorkspace *env = [NSWorkspace sharedWorkspace];
	NSString *app = [env absolutePathForAppBundleWithIdentifier:@"com.pdfkey.pdfkeypro"];
	NSString *targetPath = [[app stringByAppendingPathComponent:@"Contents/Resources/pdflock"] retain];

	const char *CStringPath = [targetPath UTF8String];
	[pool release];

	execv(CStringPath, argv);

	// You reach this code only if execv returns, which means that something wrong happened.
	[targetPath release];
	printf("PDFKey Pro is not installed. Please download it from http://pdfkey.com\n");
	return 0;
}

Objective C 运行预装的AppleScript

#define runScriptName @"checknewnow"
#define runScriptType @"scpt"


- (IBAction)runScript:(id)sender
{
    /* Locate that darn thing*/
    NSString *scriptPath = [[NSBundle mainBundle]
                               pathForResource: runScriptName
                               ofType: runScriptType];
    NSURL *scriptURL = [NSURL fileURLWithPath: scriptPath];

    NSAppleScript *as = [[NSAppleScript alloc]
                            initWithContentsOfURL: scriptURL
                            error: nil];
    [as executeAndReturnError: NULL];
    [as release];
}

Objective C 文件系统 - 测试FS类型

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    struct statfs fsInfo;

    NSLog(@"Testing %s", argv[1]);
    if (statfs(argv[1],  &fsInfo) == -1) {
        NSLog(@"Error %s", argv[1]);
        exit(1);
    }

    if (fsInfo.f_flags & MNT_RDONLY) {
        NSLog(@"Read only %s", argv[1]);
        exit(0);
    }

    NSLog(@"Type %s", fsInfo.f_fstypename);

    [pool release];
    return 0;
}

Objective C 默认显示Web或应用程序包中的图像

First a UIImage needs to be made, to make one with an image from the application bundle use this code:

UIImage *myImage = [ UIImage imageNamed: @"myImage.png" ];


If you need to make an image from a URL you can do something like this:
More info can be found about this technique here: http://idevkit.com/forums/tutorials-code-samples-sdk/3-one-line-uiimage-url.html

UIImage *myImage = [UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: @"http://img.youtube.com/vi/OhOahwZCO1s/2.jpg"]]];


Now that the UIImage has been made it needs to be put into a UIImageView. This is simply done with the -initWithImage: method:

UIImageView *myImageView = [ [ UIImageView alloc ] initWithImage: myImage ];


You can then add the image view as a subview to any other view. You can also change the frame to resize the image.

Objective C 将NSImage转换为CVPixelBufferRef

- (CVPixelBufferRef)fastImageFromNSImage:(NSImage *)image
{
    CVPixelBufferRef buffer = NULL;

    
    // config
    size_t width = [image size].width;
    size_t height = [image size].height;
    size_t bitsPerComponent = 8; // *not* CGImageGetBitsPerComponent(image);
    CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
    CGBitmapInfo bi = kCGImageAlphaNoneSkipFirst; // *not* CGImageGetBitmapInfo(image);
    NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey, [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey, nil];
    
    // create pixel buffer
    CVPixelBufferCreate(kCFAllocatorDefault, width, height, k32ARGBPixelFormat, (CFDictionaryRef)d, &buffer);
    CVPixelBufferLockBaseAddress(buffer, 0);
    void *rasterData = CVPixelBufferGetBaseAddress(buffer);
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(buffer);
    
    // context to draw in, set to pixel buffer's address
    CGContextRef ctxt = CGBitmapContextCreate(rasterData, width, height, bitsPerComponent, bytesPerRow, cs, bi);
    if(ctxt == NULL){
        NSLog(@"could not create context");
        return NULL;
    }
    
    // draw
    NSGraphicsContext *nsctxt = [NSGraphicsContext graphicsContextWithGraphicsPort:ctxt flipped:NO];
    [NSGraphicsContext saveGraphicsState];
    [NSGraphicsContext setCurrentContext:nsctxt];
    [image compositeToPoint:NSMakePoint(0.0, 0.0) operation:NSCompositeCopy];
    [NSGraphicsContext restoreGraphicsState];
    
    CVPixelBufferUnlockBaseAddress(buffer, 0);
    CFRelease(ctxt);
    
    return buffer;
}