自定义Class

#import 
@interface MyClass : NSObject
+ (id) allocAndInit;
@end

The implementation of this class method will be very straightforward. A simple allo-cation followed by an initialization:
#import "MyClass.h"
@implementation MyClass
+ (id) allocAndInit{
  MyClass *result = [[MyClass alloc] init];
  return result;
}
@end
#import "AppDelegate.h"
#import "MyClass.h"
@implementation AppDelegate
- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    MyClass *instance1 = [MyClass allocAndInit];
    NSLog(@"Instance 1 = %@", instance1);
    self.window = [[UIWindow alloc]
                   initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

Recipe-mutableString--Comparing Values

NSString *haystack = @"My Simple String";
NSString *needle = @"simple";
NSRange  range = [haystack rangeOfString:ne
                                 options:NS
if (range.location == NSNotFound){
  /* Could NOT find needle in haystack */
} else {
  /* Found the needle in the haystack */
  NSLog(@"Found %@ in %@ at location %lu",
        needle,
        haystack,
        (unsigned long)range.location);
}
NSMutableString *mutableString =
  [[NSMutableString alloc] initWithString:@"My MacBook"];
/* Add string to the end of this string */
[mutableString appendString:@" Pro"];
/* Remove the "My " string from the string */
[mutableString
 replaceOccurrencesOfString:@"My "
 withString:[NSString string] /* Empty string */
 options:NSCaseInsensitiveSearch /* Case-insensitive */
 range:NSMakeRange(0, [mutableString length])]; /* All to the end */
NSLog(@"mutableString = %@", mutableString)

When the mutableString string gets printed to the console, you will see this:
mutableString = MacBook Pro

Comparing Values in Objective-C with an if Statement

NSString *shortString = @"Hello!";
if ([shortString length] == 0)
  NSLog(@"This is an empty string");
else
  NSLog(@"This is not an empty string.");

ios6手势代码

- (IBAction)buttonAlert:(UIButton *)sender {
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message Title" message:@"Message content from you" delegate:nil cancelButtonTitle:@"Dismiss Button" otherButtonTitles:@"other button title" , nil];
    
    [alert show];
}
//
//  GestureViewController.h
//  Gesture
//
//  Created by xushao on 13-2-21.
//  Copyright (c) 2013年 xushao. All rights reserved.
//

#import 
#import 

@interface GestureViewController : UIViewController

- (IBAction)reconiger:(UIPanGestureRecognizer *)sender;

- (IBAction)rotation:(UIRotationGestureRecognizer *)sender;

- (IBAction)pinch:(UIPinchGestureRecognizer *)sender;

@property (nonatomic, strong) AVAudioPlayer *moderPlayer;

-(void) handleTap: (UITapGestureRecognizer *) recognier;
@end

//
//  GestureViewController.m
//  Gesture
//
//  Created by xushao on
//  Copyright (c) 2013年 xushao. All rights reserved.
//

#import "GestureViewController.h"

@interface GestureViewController ()

@end

@implementation GestureViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Moderato" ofType:@"mp3"]];
    NSError *error = nil;
    _moderPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    
    if (error) {
        NSLog(@"%@", [error localizedDescription]);
    }else{
    
    [_moderPlayer prepareToPlay];
    }
    
    UIGestureRecognizer *panGesture = [[UIGestureRecognizer alloc] initWithTarget:self action:@selector(reconiger:)];
    
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)reconiger:(UIPanGestureRecognizer *)sender {
    
    CGPoint translation = [sender translationInView:self.view];
    
    sender.view.center = CGPointMake(sender.view.center.x+translation.x,sender.view.center.y+ translation.y);
    
    [sender setTranslation:CGPointMake(0, 0) inView:self.view];
}

- (IBAction)rotation:(UIRotationGestureRecognizer *)sender {
    sender.view.transform = CGAffineTransformRotate(sender.view.transform, sender.rotation);
    sender.rotation = 0;
}

- (IBAction)pinch:(UIPinchGestureRecognizer *)sender {
    
    sender.view.transform = CGAffineTransformScale(sender.view.transform, sender.scale, sender.scale);
    
    sender.scale = 1;
    
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

-(void)handleTap:(UITapGestureRecognizer *)recognier{
    [_moderPlayer play];
    
}


@end

IOS6手势识别器:Simultaneously同时触发多个动作

#import 
#import 

@interface UIView (Transform)
@property (readonly) CGFloat rotation;
@property (readonly) CGFloat scaleX;
@property (readonly) CGFloat scaleY;
@end
#import "UIView-Transform.h"

// e.g. NSLog(@"Xscale: %f YScale: %f Rotation: %f", self.xscale, self.yscale, self.rotation * (180 / M_PI));

@implementation UIView (Transform)
- (CGFloat) scaleX
{
    CGAffineTransform t = self.transform;
    return sqrt(t.a * t.a + t.c * t.c);
}

- (CGFloat) scaleY
{
    CGAffineTransform t = self.transform;
    return sqrt(t.b * t.b + t.d * t.d);
}

- (CGFloat) rotation
{
    CGAffineTransform t = self.transform;
    return atan2f(t.b, t.a); 
}
@end
//dragView.h
#import 

@interface DragView : UIImageView 
{
	CGFloat tx; // x translation
	CGFloat ty; // y translation
	CGFloat scale; // zoom scale
	CGFloat theta; // rotation angle
}
@end
//DragView.M
#import "DragView.h"
#import "UIView-Transform.h"

@implementation DragView
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	// Promote the touched view
	[self.superview bringSubviewToFront:self];

	// initialize translation offsets
	tx = self.transform.tx;
	ty = self.transform.ty;
    scale = self.scaleX;
    theta = self.rotation;
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	UITouch *touch = [touches anyObject];
	if (touch.tapCount == 3)
	{
		// Reset geometry upon triple-tap
		self.transform = CGAffineTransformIdentity;
		tx = 0.0f; ty = 0.0f; scale = 1.0f;	theta = 0.0f;
	}
}

- (void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
	[self touchesEnded:touches withEvent:event];
}

- (void) updateTransformWithOffset: (CGPoint) translation
{
	// Create a blended transform representing translation, rotation, and scaling
	self.transform = CGAffineTransformMakeTranslation(translation.x + tx, translation.y + ty);
	self.transform = CGAffineTransformRotate(self.transform, theta);
    
    // Guard against scaling too low, by limiting the scale factor
    if (scale > 0.5f)
        self.transform = CGAffineTransformScale(self.transform, scale, scale);
    else
        self.transform = CGAffineTransformScale(self.transform, 0.5f, 0.5f);
}

- (void) handlePan: (UIPanGestureRecognizer *) uigr
{
	CGPoint translation = [uigr translationInView:self.superview];
	[self updateTransformWithOffset:translation];
}

- (void) handleRotation: (UIRotationGestureRecognizer *) uigr
{
	theta = uigr.rotation;
	[self updateTransformWithOffset:CGPointZero];
}

- (void) handlePinch: (UIPinchGestureRecognizer *) uigr
{
	scale = uigr.scale;
	[self updateTransformWithOffset:CGPointZero];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
	return YES;
}


- (id) initWithImage:(UIImage *)image
{
	// Initialize and set as touchable
	if (!(self = [super initWithImage:image])) return self;
	
	self.userInteractionEnabled = YES;
	
	// Reset geometry to identities
	self.transform = CGAffineTransformIdentity;
	tx = 0.0f; ty = 0.0f; scale = 1.0f;	theta = 0.0f;

	// Add gesture recognizer suite
	UIRotationGestureRecognizer *rot = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotation:)];
	UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
	UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
	self.gestureRecognizers = @[rot, pinch, pan];
	for (UIGestureRecognizer *recognizer in self.gestureRecognizers) recognizer.delegate = self;
	
	return self;
}
@end

/*
 Erica Sadun, http://ericasadun.com
 iPhone Developer's Cookbook, 6.x Edition
 BSD License, Use at your own risk
 */

#import 
#import "DragView.h"

#define COOKBOOK_PURPLE_COLOR	[UIColor colorWithRed:0.20392f green:0.19607f blue:0.61176f alpha:1.0f]
#define BARBUTTON(TITLE, SELECTOR) 	[[UIBarButtonItem alloc] initWithTitle:TITLE style:UIBarButtonItemStylePlain target:self action:SELECTOR]

@interface TestBedViewController : UIViewController
{
    DragView *sunView;
}
@end

@implementation TestBedViewController
- (void) viewDidAppear:(BOOL)animated
{
    sunView = [[DragView alloc] initWithImage:[UIImage imageNamed:@"sun.png"]];
    [self.view addSubview:sunView];
    sunView.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds));
}

- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    sunView.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds));
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}
@end

#pragma mark -

#pragma mark Application Setup
@interface TestBedAppDelegate : NSObject 
{
	UIWindow *window;
}
@end
@implementation TestBedAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{	
    [application setStatusBarHidden:YES];
    [[UINavigationBar appearance] setTintColor:COOKBOOK_PURPLE_COLOR];
    
	window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
	TestBedViewController *tbvc = [[TestBedViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:tbvc];
    window.rootViewController = nav;
	[window makeKeyAndVisible];
    return YES;
}
@end
int main(int argc, char *argv[]) {
    @autoreleasepool {
        int retVal = UIApplicationMain(argc, argv, nil, @"TestBedAppDelegate");
        return retVal;
    }
}

ios中View.Bounds和View.Frame区别

搞iOS开发的童鞋基本都会用过UIView,那他的bounds和frame两个属性也不会陌生,那这两个有什么实质性的区别呢?
先看到下面的代码你肯定就明白了一些:
-(CGRect)frame{
return CGRectMake(self.frame.origin.x,self.frame.origin.y,self.frame.size.width,self.frame.size.height);
}
-(CGRect)bounds{
return CGRectMake(0,0,self.frame.size.width,self.frame.size.height);
}
很明显,bounds的原点是(0,0)点,而frame的原点却是任意的

11

22

33

UIPanGestureRecognizer

//
//  GestureViewController.h
//  Gesture
//
//  Created by xushao on .
//  Copyright (c) 2013年 xushao. All rights reserved.
//

#import 

@interface GestureViewController : UIViewController

- (IBAction)reconiger:(UIPanGestureRecognizer *)sender;

- (IBAction)rotation:(UIRotationGestureRecognizer *)sender;

- (IBAction)pinch:(UIPinchGestureRecognizer *)sender;

@end

//
//  GestureViewController.m
//  Gesture
//
//  Created by xushao on 
//  Copyright (c) 2013年 xushao. All rights reserved.
//

#import "GestureViewController.h"

@interface GestureViewController ()

@end

@implementation GestureViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)reconiger:(UIPanGestureRecognizer *)sender {
    
    CGPoint translation = [sender translationInView:self.view];
    
    sender.view.center = CGPointMake(sender.view.center.x+translation.x,sender.view.center.y+ translation.y);
    
    [sender setTranslation:CGPointMake(0, 0) inView:self.view];
}

- (IBAction)rotation:(UIRotationGestureRecognizer *)sender {
    sender.view.transform = CGAffineTransformRotate(sender.view.transform, sender.rotation);
    sender.rotation = 0;
}

- (IBAction)pinch:(UIPinchGestureRecognizer *)sender {
    
    sender.view.transform = CGAffineTransformScale(sender.view.transform, sender.scale, sender.scale);
    
    sender.scale = 1;
    
}
//可能注意到如果你放一根手指在猴子上,放另一根在香蕉上,你能同时拖动他们,有点酷,是不是?

然而,你将会注意到如果你试着到处拖动猴子的中途,放下第二根手指企图二指拨动来缩放猴子,这是不起作用的。默认情况下,一旦视图上的一个手势识别器“认领”了这个手势,那之后其他手势识别器就不能再识别这个手势。

可是,你能通过覆盖UIGestureRecognizer委托中的方法改变这种现状。让我们看看如何实现!
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}
@end

CGAffineTransformTranslate

两者区别:前者单单指缩放的比例; 后者是在原object 的基础上进行缩放;
    CGAffineTransformMakeScale(<#CGFloat sx#>, <#CGFloat sy#>)
    CGAffineTransformScale(<#CGAffineTransform t#>, <#CGFloat sx#>, <#CGFloat sy#>)
1.CGAffineTransformMakeTranslation每次都是以最初位置的中心点为起始参照
   CGAffineTransformTranslate每次都是以传入的transform为起始参照
   CGAffineTransformIdentity为最初状态,即最初位置的中心点
2.3个按钮,bt1,bt2,bt3,bt1和bt2控制bt3的移动
- (IBAction)bt1clicked:(id)sender {
    self.bt3.transform = CGAffineTransformMakeTranslation(10, 0);
}
- (IBAction)bt2clicked:(id)sender {
    //self.bt3.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 10, 0);
    self.bt3.transform = CGAffineTransformTranslate(self.bt3.transform, 10, 0);
}
点击bt1,第一次移动10个像素,以后都是以最初位置的中心点为起始参照,所以后续bt1无论点击多少次,按钮都在初始位置偏移10个像素的位置不动
点击bt1一次,再点击bt2一次,偏移20像素,点击bt2时,上一次按钮点击的偏移作为这次的参照
只点击bt2一次,偏移10个像素
不断点击bt2,bt3不断偏移10个像素

bt2clicked的第一句不注释:
第一次点击bt2,bt3偏移20,后续再点击,永远再第一次点击后的位置,再点击bt1,回到初始偏移10的位置(往回走了10)
点击bt1,偏移10,再点击bt2,在bt1点击基础上再偏移10,后续再点击不动( CGAffineTransformTranslate(CGAffineTransformIdentity, 10, 0);每次都是从最初位置开始偏移)
- (void)viewDidLoad
{
    [super viewDidLoad];
    UIColor *color =  [UIColor greenColor];
   
    self.view.backgroundColor =  [color colorWithAlphaComponent:0.5f];

    self.tview.rank = 11;
    self.tview.suit =@"♣";
    self.tview.faceUp = NO;
    self.tview.center = self.view.center;
    [self.view addSubview:self.tview];
    
   UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(flipCard:)];
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinch:)];
    [self.tview addGestureRecognizer:pinch];
    //[self.tview addGestureRecognizer:pan   ];
    //[self.tview addGestureRecognizer:recognizer];
	// Do any additional setup after loading the view.
    
    
    UIRotationGestureRecognizer *rotate = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotate:)];
    
    [self.tview addGestureRecognizer:rotate];

}

-(void)rotate:(UIRotationGestureRecognizer *)sender{
    self.tview.transform =  CGAffineTransformRotate(self.tview.transform, sender.rotation);
    sender.rotation = 0;
}

-(void)pinch:(UIPinchGestureRecognizer *)sender{
    self.tview.transform = CGAffineTransformScale(self.tview.transform, sender.scale, sender.scale);
    sender.scale = 1.0f;
}

-(void)pan:(UIPanGestureRecognizer *)sender{
    
    
   // CGPoint point = [sender translationInView:self.view];
    //self.tview.center = CGPointMake(self.tview.center.x+point.x, self.tview.center.y + point.y);
    //[sender setTranslation:CGPointZero inView:self.view];
    
    CGPoint point = [sender locationInView:self.view];
    self.tview.center = point;
}

IOS6–CookBook-DragView-UIPangesturerecognizer

//02 - Pan Recognizer--UIPangesturerecognizer 操作
#import 

#define COOKBOOK_PURPLE_COLOR	[UIColor colorWithRed:0.20392f green:0.19607f blue:0.61176f alpha:1.0f]
#define BARBUTTON(TITLE, SELECTOR) 	[[UIBarButtonItem alloc] initWithTitle:TITLE style:UIBarButtonItemStylePlain target:self action:SELECTOR]

@interface DragView : UIImageView
{
    CGPoint previousLocation;
}
@end

@implementation DragView
- (id) initWithImage: (UIImage *) anImage
{
    if (self = [super initWithImage:anImage])
    {
        self.userInteractionEnabled = YES;//与用户互动
        //创建一个手势识别器
        UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
        self.gestureRecognizers = @[panRecognizer];//将上面创建的手势识别器指定到当前层的默认操作器
    }
    return self;
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // Promote the touched view
    [self.superview bringSubviewToFront:self];
    
    // Remember original location
    previousLocation = self.center;
}

- (void) handlePan: (UIPanGestureRecognizer *) uigr
{    //记录手势移动距离
    CGPoint translation = [uigr translationInView:self.superview];
    self.center = CGPointMake(previousLocation.x + translation.x,
                               previousLocation.y + translation.y);
}
@end

@interface TestBedViewController : UIViewController
@end

//02b pangesturerecognizer的详细操作过程



@interface DragView : UIImageView
@end

@implementation DragView
- (id) initWithImage: (UIImage *) anImage
{
    if (self = [super initWithImage:anImage])
    {
        self.userInteractionEnabled = YES;
        UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
        self.gestureRecognizers = @[panRecognizer];
    }
    return self;
}

- (void) handlePan: (UIPanGestureRecognizer *) uigr
{
    if (uigr.state == UIGestureRecognizerStateEnded)
    {
        CGPoint newCenter = CGPointMake(self.center.x + self.transform.tx, self.center.y + self.transform.ty);
        self.center = newCenter;
        
        CGAffineTransform theTransform = self.transform;
        theTransform.tx = 0.0f;
        theTransform.ty = 0.0f;
        self.transform = theTransform;
        
        return;
    }
    
    CGPoint translation = [uigr translationInView:self.superview];
    CGAffineTransform theTransform = self.transform;
    theTransform.tx = translation.x;
    theTransform.ty = translation.y;
    self.transform = theTransform;
}
@end

@interface TestBedViewController : UIViewController
@end

//01 - Direct Manipulation直接操作
#import

#define COOKBOOK_PURPLE_COLOR [UIColor colorWithRed:0.20392f green:0.19607f blue:0.61176f alpha:1.0f]
#define BARBUTTON(TITLE, SELECTOR) [[UIBarButtonItem alloc] initWithTitle:TITLE style:UIBarButtonItemStylePlain target:self action:SELECTOR]

@interface DragView : UIImageView
{
CGPoint startLocation;
}
@end

@implementation DragView
- (id) initWithImage: (UIImage *) anImage
{
if (self = [super initWithImage:anImage])
self.userInteractionEnabled = YES;
return self;
}

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
// Calculate and store offset, and pop view into front if needed
startLocation = [[touches anyObject] locationInView:self];
[self.superview bringSubviewToFront:self];
}

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
// Calculate offset
CGPoint pt = [[touches anyObject] locationInView:self];
float dx = pt.x - startLocation.x;
float dy = pt.y - startLocation.y;
CGPoint newcenter = CGPointMake(self.center.x + dx, self.center.y + dy);

// Set new location
self.center = newcenter;
}
@end

@interface TestBedViewController : UIViewController
@end

@implementation TestBedViewController
- (CGPoint) randomFlowerPosition
{
CGFloat halfFlower = 32.0f; // half of the size of the flower

// The flower must be placed fully within the view. Inset accordingly
CGSize insetSize = CGRectInset(self.view.bounds, 2*halfFlower, 2*halfFlower).size;

// Return a random position within the inset bounds
CGFloat randomX = random() % ((int)insetSize.width) + halfFlower;
CGFloat randomY = random() % ((int)insetSize.height) + halfFlower;
return CGPointMake(randomX, randomY);
}

- (void) layoutFlowers
{
// Move every flower into a new random place
[UIView animateWithDuration:0.3f animations: ^(){
for (UIView *flowerDragger in self.view.subviews)
flowerDragger.center = [self randomFlowerPosition];}];
}

- (void) viewDidAppear:(BOOL)animated
{
[self layoutFlowers];
}

- (void) loadView
{
[super loadView];
self.view.backgroundColor = [UIColor blackColor];

NSInteger maxFlowers = 12; // number of flowers to add
NSArray *flowerArray = @[@"blueFlower.png", @"pinkFlower.png", @"orangeFlower.png"];

// Add the flowers
for (int i = 0; i < maxFlowers; i++) { NSString *whichFlower = [flowerArray objectAtIndex:(random() % flowerArray.count)]; DragView *flowerDragger = [[DragView alloc] initWithImage:[UIImage imageNamed:whichFlower]]; [self.view addSubview:flowerDragger]; } // Provide a "Randomize" button self.navigationItem.rightBarButtonItem = BARBUTTON(@"Randomize", @selector(layoutFlowers)); } - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { // Check for any off-screen flowers and move them into place CGFloat halfFlower = 32.0f; CGRect targetRect = CGRectInset(self.view.bounds, halfFlower * 2, halfFlower * 2); targetRect = CGRectOffset(targetRect, halfFlower, halfFlower); for (UIView *flowerDragger in self.view.subviews) if (!CGRectContainsPoint(targetRect, flowerDragger.center)) [UIView animateWithDuration:0.3f animations: ^(){flowerDragger.center = [self randomFlowerPosition];}]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return YES; } @end #pragma mark - #pragma mark Application Setup @interface TestBedAppDelegate : NSObject
{
UIWindow *window;
}
@end
@implementation TestBedAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[application setStatusBarHidden:YES];
[[UINavigationBar appearance] setTintColor:COOKBOOK_PURPLE_COLOR];

window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
TestBedViewController *tbvc = [[TestBedViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:tbvc];
window.rootViewController = nav;
[window makeKeyAndVisible];
return YES;
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
int retVal = UIApplicationMain(argc, argv, nil, @"TestBedAppDelegate");
return retVal;
}
}

ios音频播放AVFoundtion-AVAudioplayer

[NSBundle mainBundle]当前程序目录,用pathForResource:(NSString *) type:(NSString *)来获取该目录下的文件名;

#import 
#import 

@interface AudioPlayViewController : UIViewController


@property (strong, nonatomic) IBOutlet UISlider *volume;
@property (nonatomic, strong) AVAudioPlayer *audioPlay;

- (IBAction)play:(id)sender;
- (IBAction)pause:(id)sender;
- (IBAction)volume:(id)sender;

- (IBAction)stop:(id)sender;
@end

//
//  AudioPlayViewController.m
//  AudioPlay
//
//  Created by xushao on 
//  Copyright (c) 2013年 xushao. All rights reserved.
//

#import "AudioPlayViewController.h"

@interface AudioPlayViewController ()

@end

@implementation AudioPlayViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSError *error = nil;
    
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Moderato" ofType:@"mp3"]];
    
    _audioPlay = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    
    if (error) {
        NSLog(@"Error: %@", [error localizedDescription]);
    }else{
        [_audioPlay prepareToPlay];
    }
    
    
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)play:(id)sender {
    [_audioPlay play];
    _audioPlay.delegate = self;
}

- (IBAction)pause:(id)sender {
    [_audioPlay pause];
}

- (IBAction)volume:(id)sender {
    _audioPlay.volume = _volume.value;
}

- (IBAction)stop:(id)sender {
    [_audioPlay stop];
}

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    
}

-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error{
    NSLog(@"Decode Error");
}
@end

通过使用下面的方法得到程序的main bundle
NSBundle *myBundle = [NSBundle mainBundle];

一般我们通过这种方法来得到bundle.如果你需要其他目录的资源,可以指定路径来取得bundle
NSBundle *goodBundle;
goodBundle = [NSBundle bundleWithPath:@”~/.myApp/Good.bundle”];

一旦我们有了NSBundle 对象,那么就可以访问其中的资源了
// Extension is optional
NSString *path = [goodBundle pathForImageResource:@”Mom”];
NSImage *momPhoto = [[NSImage alloc] initWithContentsOfFile:path];

bundle中可以包含一个库. 如果我们从库得到一个class, bundle会连接库,并查找该类:
Class newClass = [goodBundle classNamed:@”Rover”];
id newInstance = [[newClass alloc] init];

如果不知到class名,也可以通过查找主要类来取得
Class aClass = [goodBundle principalClass];
id anInstance = [[aClass alloc] init];

可以看到, NSBundle有很多的用途.在这章中, NSBundle负责(在后台)加载nib文件. 我们也可以不通过NSWindowController来加载nib文件, 直接使用NSBundle:
BOOL successful = [NSBundle loadNibNamed:@”About” owner:someObject];

注意噢, 我们指定了一个对象someObject作为nib的File”s Owner
获取XML文件
NSString *filePath = [[NSBundle mainBundle] pathForResouse:@”re” ofType:@”xml”];
NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
获取属性列表
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@”ViewControllers” ofType:@”plist”]];