关于iPhone SDK示例代码解析

移动开发 iOS
本文介绍的是关于iPhone SDK示例代码解析,主要是对iphone sdk一些常用的代码进行来详解,先来看详细内容。

关于iPhone SDK示例代码解析是本文要介绍的内容,主要是对iphone sdk一些常用的代码进行来详解,来看详细内容讲解。

在Xcode里,点菜单Run > Console 就可以看到NSLog的记录.

  1. NSLog(@"log: %@ ", myString);   
  2. NSLog(@"log: %f ", myFloat);   
  3. NSLog(@"log: %i ", myInt); 

图片显示

不需要UI资源绑定,在屏幕任意处显示图片。 下面的代码可以被用到任意 View 里面。

  1. CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);   
  2. UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];   
  3. [myImage setImage:[UIImage imageNamed:@"myImage.png"]];   
  4. myImage.opaque = YES; // explicitly opaque for performance   
  5. [self.view addSubview:myImage];   
  6. [myImage release]; 

应用程序边框大小

我们应该使用"bounds"来获得应用程序边框,而不是用"applicationFrame"。"applicationFrame"还包含了一个20像素的status bar。除非我们需要那额外的20像素的status bar。

Web view

UIWebView类的调用.

  1. CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0);   
  2. UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame];   
  3. [webView setBackgroundColor:[UIColor whiteColor]];   
  4. NSString *urlAddress = @"http://www.google.com";   
  5. NSURL *url = [NSURL URLWithString:urlAddress];   
  6. NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];   
  7. [webView loadRequest:requestObj];   
  8. [self addSubview:webView];   
  9. [webView release]; 

显示网络激活状态图标

在iPhone的状态栏的左上方显示的一个icon假如在旋转的话,那就说明现在网络正在被使用。

  1. UIApplication* app = [UIApplication sharedApplication];   
  2. app.networkActivityIndicatorVisible = YES; // to stop it, set this to NO 

Animation: 一组图片

连续的显示一组图片

  1. NSArray *myImages = [NSArray arrayWithObjects:   
  2.     [UIImage imageNamed:@"myImage1.png"],   
  3.     [UIImage imageNamed:@"myImage2.png"],   
  4.     [UIImage imageNamed:@"myImage3.png"],   
  5.     [UIImage imageNamed:@"myImage4.gif"],   
  6.     nil];   
  7. UIImageView *myAnimatedView = [UIImageView alloc];   
  8. [myAnimatedView initWithFrame:[self bounds]];   
  9. myAnimatedView.animationImages = myImages;   
  10. myAnimatedView.animationDuration = 0.25; // seconds   
  11. myAnimatedView.animationRepeatCount = 0; // 0 = loops forever   
  12. [myAnimatedView startAnimating];   
  13. [self addSubview:myAnimatedView];   
  14. [myAnimatedView release]; 

Animation: 移动一个对象

让一个对象在屏幕上显示成一个移动轨迹。注意:这个Animation叫"fire and forget"。也就是说编程人员不能够在animation过程中获得任何信息(比如当前的位置)。假如你需要这个信息的话,那么就需要通过animate和定时器在必要的时候去调整x&y坐标。

  1. CABasicAnimation *theAnimation;       
  2. theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];   
  3. theAnimation.duration=1;   
  4. theAnimation.repeatCount=2;   
  5. theAnimation.autoreverses=YES;   
  6. theAnimation.fromValue=[NSNumber numberWithFloat:0];   
  7. theAnimation.toValue=[NSNumber numberWithFloat:-60];   
  8. [view.layer addAnimation:theAnimation forKey:@"animateLayer"]; 

NSString和int类型转换

下面的这个例子让一个text label显示的一个整型的值。

  1. currentScoreLabel.text = [NSString stringWithFormat:@"%d", currentScore]; 

正泽表达式 (RegEx)

当前的framework还不支持RegEx。开发人员还不能在iPhone上使用包括NSPredicate在类的regex。但是在模拟器上是可以使用NSPredicate的,就是不能在真机上支持。

可以拖动的对象items

下面展示如何简单的创建一个可以拖动的image对象:

1、创建一个新的类来继承UIImageView。

  1. @interface myDraggableImage : UIImageView {   

2、在新的类实现的时候添加两个方法:

  1. - (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {   
  2. // Retrieve the touch point   
  3.     CGPoint pt = [[touches anyObject] locationInView:self];   
  4.     startLocation = pt;   
  5.     [[self superview] bringSubviewToFront:self];   
  6. }   
  7. - (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {   
  8. // Move relative to the original touch point   
  9.     CGPoint pt = [[touches anyObject] locationInView:self];   
  10.     CGRect frame = [self frame];   
  11.     frame.origin.x += pt.x – startLocation.x;   
  12.     frame.origin.y += pt.y – startLocation.y;   
  13.     [self setFrame:frame];   

3、现在再创建一个新的image加到我们刚创建的UIImageView里面,就可以展示了。

  1. dragger = [[myDraggableImage alloc] initWithFrame:myDragRect];   
  2. [dragger setImage:[UIImage imageNamed:@"myImage.png"]];   
  3. [dragger setUserInteractionEnabled:YES]; 

震动和声音播放

下面介绍的就是如何让手机震动(注意:在simulator里面不支持震动,但是他可以在真机上支持。)

  1. AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); 

Sound will work in the Simulator, however some sound (such as looped) has been reported as not working in Simulator or even altogether depending on the audio format. Note there are specific filetypes that must be used (.wav in this example).

  1. SystemSoundID pmph;   
  2. id sndpath = [[NSBundle mainBundle]   
  3.     pathForResource:@"mySound"   
  4.     ofType:@"wav"   
  5.     inDirectory:@"/"];   
  6. CFURLRef baseURL = (CFURLRef) [[NSURL alloc] initFileURLWithPath:sndpath];   
  7. AudioServicesCreateSystemSoundID (baseURL, &pmph);   
  8. AudioServicesPlaySystemSound(pmph);       
  9. [baseURL release]; 

线程

1、创建一个新的线程:

  1. [NSThread detachNewThreadSelector:@selector(myMethod)   
  2.         toTarget:self   
  3.         withObject:nil]; 

2、创建线程所调用的方法:

  1. - (void)myMethod {   
  2.     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];   
  3. *** code that should be run in the new thread goes here ***   
  4.     [pool release];   

假如我们需要在线程里面调用主线程的方法函数,就可以用performSelectorOnMainThread来实现:

  1. [self performSelectorOnMainThread:@selector(myMethod)   
  2.     withObject:nil   
  3.     waitUntilDone:false]; 

读取crash的日记文件

假如很不幸,我们的某处代码引起了crash,那么就可以阅读这篇文章应该会有用: navigate here

如何进行测试

1、在模拟器里,点击 Hardware > Simulate Memory Warning to test. 那么我们整个程序每个页面就都能够支持这个功能了。

2、Be sure to test your app in Airplane Mode.

  1. Access properties/methods in other classes  
  2.  
  3. One way to do this is via the AppDelegate:  
  4.  
  5. myAppDelegate *appDelegate = (myAppDelegate *)[[UIApplication sharedApplication] delegate];  
  6.  
  7.  [[[appDelegate rootViewController] flipsideViewController] myMethod]; 

创建随机数

调用arc4random()来创建随机数. 还可以通过random()来创建, 但是必须要手动的设置seed跟系统时钟绑定。这样才能够确保每次得到的值不一样。所以相比较而言arc4random()更好一点。

定时器

下面的这个定时器会每分钟调用一次调用myMethod。

  1. [NSTimer scheduledTimerWithTimeInterval:1   
  2.     target:self   
  3.     selector:@selector(myMethod)   
  4.     userInfo:nil   
  5.     repeats:YES]; 

当我们需要给定时器的处理函数myMethod传参数的时候怎么办?用"userInfo"属性。

1、首先创建一个定时器:

  1. [NSTimer scheduledTimerWithTimeInterval:1   
  2.     target:self   
  3.     selector:@selector(myMethod)   
  4.     userInfo:myObject   
  5.     repeats:YES]; 

2、然后传递NSTimer对象到处理函数:

  1. -(void)myMethod:(NSTimer*)timer {   
  2. // Now I can access all the properties and methods of myObject   
  3.     [[timer userInfo] myObjectMethod];   

用"invalidate"来停止定时器:

  1. [myTimer invalidate];   
  2. myTimer = nil; // ensures we never invalidate an already invalid Timer 

应用分析

当应用程序发布版本的时候,我们可能会需要收集一些数据,比如说程序被使用的频率如何。这个时候大多数的人使用PinchMedia来实现。他们会提供我们可以很方便的加到程序里面的Obj-C代码,然后就可以通过他们的网站来查看统计数据。

Time

  1. Calculate the passage of time by using CFAbsoluteTimeGetCurrent().  
  2.  
  3. CFAbsoluteTime myCurrentTime = CFAbsoluteTimeGetCurrent(); // perform calculations here 

警告窗口

显示一个简单的带OK按钮的警告窗口。

  1. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"An Alert!"   
  2.         delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];   
  3. [alert show];   
  4. [alert release]; 

Plist文件

应用程序特定的plist文件可以被保存到app bundle的Resources文件夹。当应用程序运行起来的时候,就会去检查是不是有一个plist文件在用户的Documents文件夹下。假如没有的话,就会从app bundle目录下拷贝过来。

  1. // Look in Documents for an existing plist file   
  2. NSArray *paths = NSSearchPathForDirectoriesInDomains(   
  3.     NSDocumentDirectory, NSUserDomainMask, YES);   
  4. NSString *documentsDirectory = [paths objectAtIndex:0];   
  5. myPlistPath = [documentsDirectory stringByAppendingPathComponent:   
  6.     [NSString stringWithFormat: @"%@.plist", plistName] ];   
  7. [myPlistPath retain];   
  8. // If it’s not there, copy it from the bundle   
  9. NSFileManager *fileManger = [NSFileManager defaultManager];   
  10. if ( ![fileManger fileExistsAtPath:myPlistPath] ) {   
  11.     NSString *pathToSettingsInBundle = [[NSBundle mainBundle]   
  12.         pathForResource:plistName ofType:@"plist"];   
  13. }        

现在我们就可以从Documents文件夹去读plist文件了。

  1. NSArray *paths = NSSearchPathForDirectoriesInDomains(   
  2.     NSDocumentDirectory, NSUserDomainMask, YES);   
  3. NSString *documentsDirectoryPath = [paths objectAtIndex:0];   
  4. NSString *path = [documentsDirectoryPath   
  5.     stringByAppendingPathComponent:@"myApp.plist"];   
  6. NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path]; 

Now read and set key/values

  1. myKey = (int)[[plist valueForKey:@"myKey"] intValue];   
  2. myKey2 = (bool)[[plist valueForKey:@"myKey2"] boolValue];   
  3. [plist setValue:myKey forKey:@"myKey"];   
  4. [plist writeToFile:path atomically:YES]; 

Info button

为了更方便End-User去按,我们可以增大Info button上可以触摸的区域。

  1. CGRect newInfoButtonRect = CGRectMake(infoButton.frame.origin.x-25,   
  2.     infoButton.frame.origin.y-25, infoButton.frame.size.width+50,   
  3.     infoButton.frame.size.height+50);   
  4. [infoButton setFrame:newInfoButtonRect]; 

查找Subviews(Detecting Subviews)

我们可以通过循环来查找一个已经存在的View。当我们使用view的tag属性的话,就很方便实现Detect Subviews。

  1. for (UIImageView *anImage in [self.view subviews]) {   
  2. if (anImage.tag == 1) {   
  3. // do something   
  4.     }   

手册文档

  1. Official Apple How-To’s  
  2. Learn Objective-C 

小结:关于iPhone SDK示例代码解析的内容介绍完了,希望本文对你有所帮助!

责任编辑:zhaolei 来源: 网络转载
相关推荐

2011-08-18 10:06:10

2011-07-06 17:40:43

iPhone SDK

2011-07-06 17:53:40

iPhone SDK Xcode

2011-08-12 13:19:24

iPhoneSDK安装

2011-08-09 14:54:29

iPhoneNSDateanotherDate

2009-12-07 15:41:51

PHP图片加水印

2010-02-24 13:38:18

WCF PreCal模

2009-12-18 16:00:29

Ruby获取当前类名

2010-02-22 15:06:31

WCF信道监听器

2011-08-19 10:05:30

iPhone开发

2011-08-01 15:17:17

iPhone开发 证书 签名

2011-07-18 09:35:29

iPhone 框架

2010-03-05 15:01:29

Python解析XML

2010-01-14 13:08:37

VB.NET运算符

2011-08-12 11:22:53

Oracle存储过程Java

2021-08-04 14:32:16

鸿蒙HarmonyOS应用

2009-12-02 10:49:59

PHP解析XML元素结

2011-07-18 14:39:53

iPhone SDK UIKit

2011-07-22 18:25:20

XCode iPhone SDK

2013-12-26 15:40:33

Android SDK项目
点赞
收藏

51CTO技术栈公众号