您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發雜記(三):常用語法與工具函式備忘

編輯:iOS 開發綜合

延續上一篇,這裡整理更偏「語法層面」的常用片段,包含狀態列、隨機數、音訊播放、計時器、路徑取得、檔案操作、時間格式化與 plist 讀寫。

隱藏狀態列

[[UIApplication sharedApplication] setStatusBarHidden:YES];

取得隨機數

NSData *datanow = [NSData data];
srand((int)datanow);
int effectPicNum = rand() % 7;

播放音樂

NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:@"startLogo" ofType:@"mp3"];
NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:musicFilePath];
musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];
musicPlayer.numberOfLoops = 0;   // -1 為無限循環,0 為播放一次
[musicPlayer play];

計時器與延遲

// 每 0.8 秒呼叫一次
countTimer = [NSTimer scheduledTimerWithTimeInterval:0.8
                                              target:self
                                            selector:@selector(timeCount:)
                                            userInfo:nil repeats:YES];
[countTimer fire];

// 延遲執行
[self performSelector:@selector(test) withObject:nil afterDelay:0.1];

啟動執行緒並搭配計時器廣播

[NSThread detachNewThreadSelector:@selector(transImage) toTarget:self withObject:nil];
timer = [NSTimer scheduledTimerWithTimeInterval:0.03
                                         target:self
                                       selector:@selector(TimerClock:)
                                       userInfo:nil repeats:YES];
[timer fire];

- (void)TimerClock:(id)sender {
    if (Timecontrol > 1) {
        [timerCondition broadcast];   // 觸發等待中的 timerCondition
    }
}

取得檔案路徑

三種常見方式:

// 1. 以 NSHomeDirectory 組出路徑
NSString *homeDirectory = NSHomeDirectory();
NSString *fileDirectory = [homeDirectory stringByAppendingPathComponent:@"temp/app_data.plist"];

// 2. 用 NSSearchPathForDirectoriesInDomains 搜尋指定目錄
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"file.txt"];

// 3. 直接用 NSTemporaryDirectory 取得 tmp 全路徑
NSString *tempDirectory = NSTemporaryDirectory();

其中 NSDocumentDirectory 表示要找的目錄(若要找 Caches 則用 NSCachesDirectory),NSUserDomainMask 把搜尋限制在 App 沙盒內,最後一個參數決定是否展開「~」;一般固定傳 YES 即可。

檔案與資料夾操作

// 不存在則建立目錄
if (![[NSFileManager defaultManager] fileExistsAtPath:themePath]) {
    [[NSFileManager defaultManager] createDirectoryAtPath:themePath attributes:nil];
}

// 刪除同名既有檔案
if ([[NSFileManager defaultManager] fileExistsAtPath:savePath]) {
    [[NSFileManager defaultManager] removeItemAtPath:savePath error:NULL];
}

// 建立檔案
BOOL success = [[NSFileManager defaultManager] createFileAtPath:filepath
                                                     contents:nil
                                                   attributes:nil];

子執行緒回主執行緒

[self performSelectorOnMainThread:@selector(shiftView)
                       withObject:nil waitUntilDone:YES];

時間格式化

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd EEEE HH:mm:ss a"];
NSString *locationString = [formatter stringFromDate:[NSDate date]];
[formatter release];

大寫 H 是 24 小時制,小寫 h 是 12 小時制。常用符號:

  • y 年、M 月、d 日、E 星期(Tue)、a 上下午標記
  • H 小時(0-23)、h 小時(1-12)、k(1-24)、K(0-11)
  • m 分、s 秒、S 毫秒
  • z 時區(PST)、Z RFC 822 時區(-0800)

讀寫 plist

plist 是標準的 XML 檔案,在 Cocoa 中操作相當容易,Mac 與 iPhone 通用:

// 寫入
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:@"/Sample.plist"];
[dict setObject:@"Yes" forKey:@"RestartSpringBoard"];
[dict writeToFile:@"/Sample.plist" atomically:YES];

// 讀取
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc] initWithContentsOfFile:@"/Sample.plist"];
NSString *object = [dict2 objectForKey:@"RestartSpringBoard"];

實務上提醒兩點:createDirectoryAtPath:attributes: 與 setStatusBarHidden: 在新版 SDK 中已有替代 API,新專案請直接用 fileExistsAtPath:isDirectory: 搭配 createDirectoryAtPath:withIntermediateDirectories:attributes:error:;另外 plist 路徑不要用根目錄的 "/",那在 iOS 沙盒環境下是無效的,請改用前面提到的 Documents 或 Caches 路徑。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved