關(guān)于iPhone SDK示例代碼解析
關(guān)于iPhone SDK示例代碼解析是本文要介紹的內(nèi)容,主要是對(duì)iphone sdk一些常用的代碼進(jìn)行來詳解,來看詳細(xì)內(nèi)容講解。
在Xcode里,點(diǎn)菜單Run > Console 就可以看到NSLog的記錄.
- NSLog(@"log: %@ ", myString);
- NSLog(@"log: %f ", myFloat);
- NSLog(@"log: %i ", myInt);
圖片顯示
不需要UI資源綁定,在屏幕任意處顯示圖片。 下面的代碼可以被用到任意 View 里面。
- CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);
- UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
- [myImage setImage:[UIImage imageNamed:@"myImage.png"]];
- myImage.opaque = YES; // explicitly opaque for performance
- [self.view addSubview:myImage];
- [myImage release];
應(yīng)用程序邊框大小
我們應(yīng)該使用"bounds"來獲得應(yīng)用程序邊框,而不是用"applicationFrame"。"applicationFrame"還包含了一個(gè)20像素的status bar。除非我們需要那額外的20像素的status bar。
Web view
UIWebView類的調(diào)用.
- CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0);
- UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame];
- [webView setBackgroundColor:[UIColor whiteColor]];
- NSString *urlAddress = @"http://www.google.com";
- NSURL *url = [NSURL URLWithString:urlAddress];
- NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
- [webView loadRequest:requestObj];
- [self addSubview:webView];
- [webView release];
顯示網(wǎng)絡(luò)激活狀態(tài)圖標(biāo)
在iPhone的狀態(tài)欄的左上方顯示的一個(gè)icon假如在旋轉(zhuǎn)的話,那就說明現(xiàn)在網(wǎng)絡(luò)正在被使用。
- UIApplication* app = [UIApplication sharedApplication];
- app.networkActivityIndicatorVisible = YES; // to stop it, set this to NO
Animation: 一組圖片
連續(xù)的顯示一組圖片
- NSArray *myImages = [NSArray arrayWithObjects:
- [UIImage imageNamed:@"myImage1.png"],
- [UIImage imageNamed:@"myImage2.png"],
- [UIImage imageNamed:@"myImage3.png"],
- [UIImage imageNamed:@"myImage4.gif"],
- nil];
- UIImageView *myAnimatedView = [UIImageView alloc];
- [myAnimatedView initWithFrame:[self bounds]];
- myAnimatedView.animationImages = myImages;
- myAnimatedView.animationDuration = 0.25; // seconds
- myAnimatedView.animationRepeatCount = 0; // 0 = loops forever
- [myAnimatedView startAnimating];
- [self addSubview:myAnimatedView];
- [myAnimatedView release];
Animation: 移動(dòng)一個(gè)對(duì)象
讓一個(gè)對(duì)象在屏幕上顯示成一個(gè)移動(dòng)軌跡。注意:這個(gè)Animation叫"fire and forget"。也就是說編程人員不能夠在animation過程中獲得任何信息(比如當(dāng)前的位置)。假如你需要這個(gè)信息的話,那么就需要通過animate和定時(shí)器在必要的時(shí)候去調(diào)整x&y坐標(biāo)。
- CABasicAnimation *theAnimation;
- theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
- theAnimation.duration=1;
- theAnimation.repeatCount=2;
- theAnimation.autoreverses=YES;
- theAnimation.fromValue=[NSNumber numberWithFloat:0];
- theAnimation.toValue=[NSNumber numberWithFloat:-60];
- [view.layer addAnimation:theAnimation forKey:@"animateLayer"];
NSString和int類型轉(zhuǎn)換
下面的這個(gè)例子讓一個(gè)text label顯示的一個(gè)整型的值。
- currentScoreLabel.text = [NSString stringWithFormat:@"%d", currentScore];
正澤表達(dá)式 (RegEx)
當(dāng)前的framework還不支持RegEx。開發(fā)人員還不能在iPhone上使用包括NSPredicate在類的regex。但是在模擬器上是可以使用NSPredicate的,就是不能在真機(jī)上支持。
可以拖動(dòng)的對(duì)象items
下面展示如何簡單的創(chuàng)建一個(gè)可以拖動(dòng)的image對(duì)象:
1、創(chuàng)建一個(gè)新的類來繼承UIImageView。
- @interface myDraggableImage : UIImageView {
- }
2、在新的類實(shí)現(xiàn)的時(shí)候添加兩個(gè)方法:
- - (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
- // Retrieve the touch point
- CGPoint pt = [[touches anyObject] locationInView:self];
- startLocation = pt;
- [[self superview] bringSubviewToFront:self];
- }
- - (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
- // Move relative to the original touch point
- CGPoint pt = [[touches anyObject] locationInView:self];
- CGRect frame = [self frame];
- frame.origin.x += pt.x – startLocation.x;
- frame.origin.y += pt.y – startLocation.y;
- [self setFrame:frame];
- }
3、現(xiàn)在再創(chuàng)建一個(gè)新的image加到我們剛創(chuàng)建的UIImageView里面,就可以展示了。
- dragger = [[myDraggableImage alloc] initWithFrame:myDragRect];
- [dragger setImage:[UIImage imageNamed:@"myImage.png"]];
- [dragger setUserInteractionEnabled:YES];
震動(dòng)和聲音播放
下面介紹的就是如何讓手機(jī)震動(dòng)(注意:在simulator里面不支持震動(dòng),但是他可以在真機(jī)上支持。)
- 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).
- SystemSoundID pmph;
- id sndpath = [[NSBundle mainBundle]
- pathForResource:@"mySound"
- ofType:@"wav"
- inDirectory:@"/"];
- CFURLRef baseURL = (CFURLRef) [[NSURL alloc] initFileURLWithPath:sndpath];
- AudioServicesCreateSystemSoundID (baseURL, &pmph);
- AudioServicesPlaySystemSound(pmph);
- [baseURL release];
線程
1、創(chuàng)建一個(gè)新的線程:
- [NSThread detachNewThreadSelector:@selector(myMethod)
- toTarget:self
- withObject:nil];
2、創(chuàng)建線程所調(diào)用的方法:
- - (void)myMethod {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- *** code that should be run in the new thread goes here ***
- [pool release];
- }
假如我們需要在線程里面調(diào)用主線程的方法函數(shù),就可以用performSelectorOnMainThread來實(shí)現(xiàn):
- [self performSelectorOnMainThread:@selector(myMethod)
- withObject:nil
- waitUntilDone:false];
讀取crash的日記文件
假如很不幸,我們的某處代碼引起了crash,那么就可以閱讀這篇文章應(yīng)該會(huì)有用: navigate here
如何進(jìn)行測試
1、在模擬器里,點(diǎn)擊 Hardware > Simulate Memory Warning to test. 那么我們整個(gè)程序每個(gè)頁面就都能夠支持這個(gè)功能了。
2、Be sure to test your app in Airplane Mode.
- Access properties/methods in other classes
- One way to do this is via the AppDelegate:
- myAppDelegate *appDelegate = (myAppDelegate *)[[UIApplication sharedApplication] delegate];
- [[[appDelegate rootViewController] flipsideViewController] myMethod];
創(chuàng)建隨機(jī)數(shù)
調(diào)用arc4random()來創(chuàng)建隨機(jī)數(shù). 還可以通過random()來創(chuàng)建, 但是必須要手動(dòng)的設(shè)置seed跟系統(tǒng)時(shí)鐘綁定。這樣才能夠確保每次得到的值不一樣。所以相比較而言arc4random()更好一點(diǎn)。
定時(shí)器
下面的這個(gè)定時(shí)器會(huì)每分鐘調(diào)用一次調(diào)用myMethod。
- [NSTimer scheduledTimerWithTimeInterval:1
- target:self
- selector:@selector(myMethod)
- userInfo:nil
- repeats:YES];
當(dāng)我們需要給定時(shí)器的處理函數(shù)myMethod傳參數(shù)的時(shí)候怎么辦?用"userInfo"屬性。
1、首先創(chuàng)建一個(gè)定時(shí)器:
- [NSTimer scheduledTimerWithTimeInterval:1
- target:self
- selector:@selector(myMethod)
- userInfo:myObject
- repeats:YES];
2、然后傳遞NSTimer對(duì)象到處理函數(shù):
- -(void)myMethod:(NSTimer*)timer {
- // Now I can access all the properties and methods of myObject
- [[timer userInfo] myObjectMethod];
- }
用"invalidate"來停止定時(shí)器:
- [myTimer invalidate];
- myTimer = nil; // ensures we never invalidate an already invalid Timer
應(yīng)用分析
當(dāng)應(yīng)用程序發(fā)布版本的時(shí)候,我們可能會(huì)需要收集一些數(shù)據(jù),比如說程序被使用的頻率如何。這個(gè)時(shí)候大多數(shù)的人使用PinchMedia來實(shí)現(xiàn)。他們會(huì)提供我們可以很方便的加到程序里面的Obj-C代碼,然后就可以通過他們的網(wǎng)站來查看統(tǒng)計(jì)數(shù)據(jù)。
Time
- Calculate the passage of time by using CFAbsoluteTimeGetCurrent().
- CFAbsoluteTime myCurrentTime = CFAbsoluteTimeGetCurrent(); // perform calculations here
警告窗口
顯示一個(gè)簡單的帶OK按鈕的警告窗口。
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"An Alert!"
- delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
- [alert show];
- [alert release];
Plist文件
應(yīng)用程序特定的plist文件可以被保存到app bundle的Resources文件夾。當(dāng)應(yīng)用程序運(yùn)行起來的時(shí)候,就會(huì)去檢查是不是有一個(gè)plist文件在用戶的Documents文件夾下。假如沒有的話,就會(huì)從app bundle目錄下拷貝過來。
- // Look in Documents for an existing plist file
- NSArray *paths = NSSearchPathForDirectoriesInDomains(
- NSDocumentDirectory, NSUserDomainMask, YES);
- NSString *documentsDirectory = [paths objectAtIndex:0];
- myPlistPath = [documentsDirectory stringByAppendingPathComponent:
- [NSString stringWithFormat: @"%@.plist", plistName] ];
- [myPlistPath retain];
- // If it’s not there, copy it from the bundle
- NSFileManager *fileManger = [NSFileManager defaultManager];
- if ( ![fileManger fileExistsAtPath:myPlistPath] ) {
- NSString *pathToSettingsInBundle = [[NSBundle mainBundle]
- pathForResource:plistName ofType:@"plist"];
- }
現(xiàn)在我們就可以從Documents文件夾去讀plist文件了。
- NSArray *paths = NSSearchPathForDirectoriesInDomains(
- NSDocumentDirectory, NSUserDomainMask, YES);
- NSString *documentsDirectoryPath = [paths objectAtIndex:0];
- NSString *path = [documentsDirectoryPath
- stringByAppendingPathComponent:@"myApp.plist"];
- NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];
Now read and set key/values
- myKey = (int)[[plist valueForKey:@"myKey"] intValue];
- myKey2 = (bool)[[plist valueForKey:@"myKey2"] boolValue];
- [plist setValue:myKey forKey:@"myKey"];
- [plist writeToFile:path atomically:YES];
Info button
為了更方便End-User去按,我們可以增大Info button上可以觸摸的區(qū)域。
- CGRect newInfoButtonRect = CGRectMake(infoButton.frame.origin.x-25,
- infoButton.frame.origin.y-25, infoButton.frame.size.width+50,
- infoButton.frame.size.height+50);
- [infoButton setFrame:newInfoButtonRect];
查找Subviews(Detecting Subviews)
我們可以通過循環(huán)來查找一個(gè)已經(jīng)存在的View。當(dāng)我們使用view的tag屬性的話,就很方便實(shí)現(xiàn)Detect Subviews。
- for (UIImageView *anImage in [self.view subviews]) {
- if (anImage.tag == 1) {
- // do something
- }
- }
手冊(cè)文檔
- Official Apple How-To’s
- Learn Objective-C
小結(jié):關(guān)于iPhone SDK示例代碼解析的內(nèi)容介紹完了,希望本文對(duì)你有所幫助!