Objective C 计算两个纬度/经度之间的距离

CLLocation *userLoc = [[CLLocation alloc] initWithCoordinate:appDelegate.mapView2.userLocation.coordinate];
CLLocation *poiLoc = [[CLLocation alloc] initWithLatitude: [aPOI.latitude doubleValue] longitude: [aPOI.longitude doubleValue]];
	
double dist = [userLoc getDistanceFrom:poiLoc] / 1000;
	
NSLog(@"%f",dist);

Objective C 从XIB加载可重用的UITableViewCell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"CustomCellId"];
    if (cell == nil) {
        UIViewController *c = [[UIViewController alloc] 
                                                   initWithNibName:@"CustomCell" bundle:nil];

        cell = (PostCell *)c.view;
        [c release];
    }
    return cell;
}

Objective C 从XIB版本2加载可重用的UITableViewCell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
            PersonDetailsInfoCell *cell = (PersonDetailsInfoCell *)[tableView dequeueReusableCellWithIdentifier:@"PersonDetailsInfoCell"];
            if ( cell == nil ) // i.e. there isn't a reusable one I can use.
            {
                
                // wierd boilerplate code for loading the cell from a NIB.. 
                NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"PersonDetailsInfoCell" owner:self options:nil];
                id firstObject = [topLevelObjects objectAtIndex:0];
                if ( [ firstObject isKindOfClass:[UITableViewCell class]] )
                    cell = firstObject;     
                else cell = [topLevelObjects objectAtIndex:1];
            }
            
            // set up properties...
            
            return cell;
    }

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 68.0; // return the HEIGHT of your cell as you designed it in IB.
}

Objective C 查看动画

#import <QuartzCore/QuartzCore.h>	
{
CATransition *transition = [CATransition animation];
	transition.duration = 0.75;
	transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
	
	NSString *types[4] = {kCATransitionMoveIn, kCATransitionPush, kCATransitionReveal, kCATransitionFade};
	NSString *subtypes[4] = {kCATransitionFromLeft, kCATransitionFromRight, kCATransitionFromTop, kCATransitionFromBottom};

	transition.type = types[3];
	transition.subtype = subtypes[1];
	transition.delegate = self;
	
	[containerView.layer addAnimation:transition forKey:nil];
	
	[view1 removeFromSuperview];
	[containerView addSubview:view2];
}

Objective C 缩小图像

+ (UIImage*)imageWithImage:(UIImage*)image 
			  scaledToSize:(CGSize)newSize;
{
	UIGraphicsBeginImageContext( newSize );
	[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
	UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	
	return newImage;
}

Objective C 保存图像示例

NSString *documentsPath = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"];
	
NSString *filePath = [documentsPath stringByAppendingPathComponent: @"selectedImage.png"];
	
int i = 0;
	
while ( [[NSFileManager defaultManager] fileExistsAtPath: filePath] )
	{
		filePath = [NSString stringWithFormat: @"%@/%@-%d.@%@", documentsPath, @"selectedImage", ++i, @"png"];
	}

[NSImagePNGRepresentation(image) writeToFile: filePath atomically: YES]

Objective C 添加到OS X状态托盘

@interface Tray : NSObject <NSApplicationDelegate> {
	NSStatusItem *trayItem;
}
@end

@implementation Tray

- (IBAction)testAction:(id)sender;
{
	NSLog(@"Hello World");
}

- (IBAction)quitAction:(id)sender;
{
	[NSApp terminate:sender];
}

- (void)applicationDidFinishLaunching:(NSNotification *)note;
{
	NSZone *zone = [NSMenu menuZone];
	NSMenu *menu = [[[NSMenu allocWithZone:zone] init] autorelease];
	NSMenuItem *item;
	
	item = [menu addItemWithTitle:@"Testing" action:@selector(testAction:) keyEquivalent:@""];
	[item setTarget:self];
	
	item = [menu addItemWithTitle:@"Quit" action:@selector(quitAction:) keyEquivalent:@""];
	[item setTarget:self];
	
	trayItem = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];
	[trayItem setMenu:menu];
	[trayItem setHighlightMode:YES];
	[trayItem setTitle:@"HERE"];
}

- (void)dealloc;
{
	[trayItem release];
	[super dealloc];
}

@end

Objective C 带有nil头字段的BxMailer附件

#import "MyHandler.h"

@implementation MyHandler

- (id)renderWithTransport:(BxTransport *)transport {
    if (! [transport.requestPath isEqualToString:@"/favicon.ico"]) {
        BxMailerAttachment *attachment = [[[BxMailerAttachment alloc] initWithName:@"cheese.jpg" path:@"/Users/dblais/Desktop/selected.png"] autorelease];
        [[BxMailer systemMailer] sendMessage:@"The Message"
                                     subject:@"The Subject"
                                          to:@"dominic@bombaxtic.com"
                                        from:@"dominic@bombaxtic.com"
                                     headers:nil
                                 attachments:attachment, nil];
    }
    return self;
}

@end

Objective C 在iPhone上显示Google地图上的路线。

- (void)showDirections {
	if ([self.address length] == 0) return;
	//We create our link to the appDelegate
	ClubPlanetControllerAppDelegate * appDelegate = (ClubPlanetControllerAppDelegate *)[UIApplication sharedApplication].delegate;

	
	NSURL *myURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://maps.google.com/maps?daddr==%@&saddr=%f,%f", [self.address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [appDelegate.lat floatValue], [appDelegate.lon floatValue]]];
	[[UIApplication sharedApplication] openURL:myURL];
}

Objective C iPhone视图自动旋转视图更新 - 标题和实现

// Source @ http://www.jailbyte.ca/safari/files/SpinView.zip
//
//  UntitledViewController.h
//  SpinView
//
//  Created by Richard Vacheresse on 10-05-20.
//  Copyfright jailByte.ca 2010. Use it anyway you like.
//

#import <UIKit/UIKit.h>

@interface UntitledViewController : UIViewController
{
	//-view (the image) used for manipulation by the accelerometer
	UIImageView *imageView;
}

@property (nonatomic, retain) UIImageView *imageView;

- (IBAction) actionBtnOne;

@end

---------------------------------------------------------------------------

//
//  UntitledViewController.m
//
//  SpinView - this is an example of how to deal with the rotation of views via the accelerometer and the
//  overridden method shouldAutorotateToInterfaceOrientation. this example uses an image view as the view
//	that is being rotated; this imageview is created with the press of a button, the resulting action is to
//	simply show the layer in the view. from there you start to spin the device and the updates follow. to reset
//  the view you must press the home key and then restart the app; sorry, just too lazy to add anymore.
//
//	**note: there is a bug to this solution, and it becomes apparent when using the device and the user rotates
//	the phone quickly 180 degrees. i believe it may have something to do with when the floats that are used
//	to hold the x and y values are updated while rotating; like it grabs the coordinates while spinnning past 90
//	degrees. the next time you rotate the view, the view will correct itself.
//
//  Created by Richard Vacheresse on 10-05-20.
//  Copyfright jailByte.ca 2010. Use it anyway you like.
//

#import "UntitledViewController.h"

@implementation UntitledViewController

@synthesize imageView;

- (void)viewDidLoad
{
    [super viewDidLoad];
	
	//-create a button
	UIButton *btnOne = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[btnOne setTitle: @"btnOne" forState: UIControlStateNormal];
	[btnOne setFrame:CGRectMake(0.0f, 0.0f, 105.0f, 55.0f)];
	[btnOne setCenter:CGPointMake(160.0f, 55.0f)];
	[btnOne addTarget:self action:@selector(actionBtnOne) forControlEvents:UIControlEventTouchUpInside];
	//-add it to the display
	[self.view addSubview: btnOne];
}

//
//	actionBtnOne - initializes a UIImageView, sets the initial properties, add it to the display, then releases it.
//	
- (IBAction) actionBtnOne
{
	imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 480.0f)];
	[imageView setImage:[UIImage imageNamed:@"image.png"]];
	[imageView setAutoresizesSubviews: YES];
	[self.view addSubview:imageView];
	[imageView release];
}

//
//	shouldAutorotateToInterfaceOrientation - used to interact with the accelerometer; this is an overriden method.
//	
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	if ( interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight)
	{		
		//-set the center of the image from the dimensions of the display
		//-x value is +10 due to status bar
		[UIView beginAnimations: nil context: NULL];
		[UIView setAnimationDuration: 0.25];
		CGFloat x = self.view.bounds.size.height / 2 + 10;
		CGFloat y = self.view.bounds.size.width / 2;
		CGPoint center = CGPointMake( x, y); 
		[imageView setCenter: center];
		[UIView commitAnimations];
		
		[UIView beginAnimations: nil context: NULL];
		[UIView setAnimationDuration: 0.25];
		
		//-this will keep it in the same position - always standing up
		//CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI / 0.5);
		
		//this will keep it standing up as in portrait however it will turn it upsidedown
		//CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI / 1.0);
		
		//this will change the view to be upside-down but in proper alignment with the landscape mode
		//CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI / 2.0);
		
		//this will change the view to be rightside-up in proper alignment with landscape mode
		CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI / -2.0);
		
		imageView.transform = transform;
		[UIView commitAnimations];
		
	}
	else
	{
		//-set the center of the image from the dimensions of the display
		//-x value is +10 due to status bar
		[UIView beginAnimations: nil context: NULL];
		[UIView setAnimationDuration: 0.25];
		CGFloat x = self.view.bounds.size.height / 2 + 10;
		CGFloat y = self.view.bounds.size.width / 2;
		CGPoint center = CGPointMake( x, y); 
		[imageView setCenter: center];
		[UIView commitAnimations];
		
		[UIView beginAnimations: nil context: NULL];
		[UIView setAnimationDuration: 0.25];
		CGAffineTransform move = CGAffineTransformMakeTranslation(0.0f, 0.0f);
		imageView.transform = move;
		CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI * 2);
		imageView.transform = transform;
		[UIView commitAnimations];
	}
	
    // Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait ||
			interfaceOrientation == UIInterfaceOrientationLandscapeRight ||
			interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
			interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown);
}

- (void)dealloc
{
	[imageView release];
    [super dealloc];
}

//-the
@end