2015年4月11日 星期六

inline function 內嵌函數

在你宣告的function之前加上inline關鍵字
代表的是你想要在編譯時,直接把這個函式的內容寫進呼叫它的函式中。
原因是
在機器碼中,每個函式會寫到不同的記憶體位置,程式在執行呼叫時,會先停下來目前的狀態,跳到被呼叫的函式的記憶體區塊,執行完之後再跳回來。
在這段跳轉的過程中是會消耗系統資源的......
所以如果你的函式很短,或沒有要做什麼複雜計算,可以在編譯時,把被呼叫函式中的程式碼直接寫到目前的函式之中,來省下這段記憶體跳轉所造成的消耗。

note. inline只能用來建議編譯器你"想"這麼做,實際結果還是要看編譯器考慮到有沒有什麼限制而定。

2015年4月4日 星期六

判斷iOS現在是否為24時制

class func is24HourTimeFormat() -> Bool {
        var dateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = NSDateFormatterStyle.NoStyle
        dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
        dateFormatter.locale = (NSLocale.currentLocale())
        var dateString = dateFormatter.stringFromDate(NSDate())
        let amRange = dateString.rangeOfString(dateFormatter.AMSymbol)
        let pmRange = dateString.rangeOfString(dateFormatter.PMSymbol)
        return (amRange == nil && pmRange == nil)

    }

2015年3月31日 星期二

設定textView的邊界留白

//在scrollView是contentInset,但textView被改到textContainerInset屬性
self.textView.textContainerInset = UIEdgeInsetsMake(25, 25, 25, 25)

2015年3月26日 星期四

Literal Expression

println(__FILE__) //顯示當下檔案的路徑
println(__LINE__) //顯示當下在這支檔案的那一行
println(__COLUMN__) //顯示當下在這支檔案的那一列
println(__FUNCTION__) //顯示當下func的名稱

全域函式 vs 巢狀函式 vs 閉包

全域函式
在swift中你可以直接開一個檔案來宣告func,這些func可提供全域使用

巢狀函式
一般宣告在class的 func都是,這種可以取用他domain range中的其他變數來用

閉包
這裡不需要宣告func name,也只可以取用宣告給它的參數來用

2015年3月19日 星期四

想在非主線程加入NSTimer,要放進Runloop中跑才能執行function

//建立Timer
let timer = NSTimer(timeInterval: self.responseTimeoutInterval, target: self, selector: Selector("responseTimeout:"), userInfo: Int(packet.header.transactionId), repeats: false)
            NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)

//接收事件的function
dynamic func responseTimeout(timer: NSTimer) {
        logDebug(TAG, "responseTimeout")
        if let transactionId = timer.userInfo as? Int {
            self.resetResponseTimer(transactionId)
        }
        self.delegate?.onError(NSError(domain: fusionErrorDomain, code: Int(FusionErrorCode.ResponseTimeout.rawValue), userInfo: nil))
        self.socket?.disconnect()
    }

2015年3月18日 星期三

統一收notification再以delegate分派出去的設計方式

//在UIEvents統一接收notification
@objc protocol UIEvents {
    func onError(notification: NSNotification)
}

class UIEventHelper {

    class func registerFusionEvents(eventReceiver: AnyObject) {
        NSNotificationCenter.defaultCenter().addObserver(
            eventReceiver, selector: "onFusionError:",
            name: FusionService.fusionErrorNotification, object: nil)

    }
}

//在你要使用的class,加入註冊跟實作delegate
//viewWillAppear
self.registerNotifications()
//viewWillDisappear
self. unregisterNotifications()

    // MARK: - Notification
func registerNotifications() {
    UIEventHelper.registerFusionEvents(self)
}
    
func unregisterNotifications() {
    UIEventHelper.unregisterUIEvents(self)
}

func onError(notification: NSNotification) {
//TODO:實作你的code
}