當我們今天有一個 Class A 用到了 Class B 的物件,一般情況下,需要在 A 的代碼中顯示的 new 一個 B 的物件。這樣子Class A 的建構就依賴於 Class B了, 當我們實現依賴注入之後 A 的代碼只需要定義一個私有的 B 物件,不需要直接 New 來獲得這個物件,而是透過相關的容器控制程式來將 B 物件在外部 new出來並注入到 A 類裡的參考中。
var timer : Timer? overridefuncviewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. timer =Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(fire), userInfo: nil, repeats: false) }
overridefuncdidReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objcfuncfire() { //Do some thing } deinit { timer?.invalidate() timer =nil; } }
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 150(offset:150).state:153 at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5504) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5440) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5436) at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2224) at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1551) at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511) at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:595) at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583) at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3312) at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1618) at android.support.v7.widget.RecyclerView$ViewFlinger.run(RecyclerView.java:4702) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911) at android.view.Choreographer.doCallbacks(Choreographer.java:686) at android.view.Choreographer.doFrame(Choreographer.java:619) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:7409) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)