Created
May 3, 2017 16:20
-
-
Save yamazaki-sensei/347ec3bf7cdc0ae67912af4ac196d87d to your computer and use it in GitHub Desktop.
がっつりiOSをやった人がAndroidに移るとListenerの実装でハマるかもしれない話 ref: http://qiita.com/almichest/items/efd3b2ca25939d05106d
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import UIKit | |
| // UI | |
| class ViewController: UIViewController, ModelDelegate { | |
| let model = Model() | |
| override func viewDidLoad() { | |
| super.viewDidLoad() | |
| model.delegate = self | |
| } | |
| func notify(model: Model) { | |
| } | |
| } | |
| // Modelと通知用のprotocol | |
| protocol ModelDelegate: class { | |
| func notify(model: Model) | |
| } | |
| class Model { | |
| weak var delegate: ModelDelegate? | |
| func doSomething() { | |
| // 何かする | |
| delegate?.notify(model: self) | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import android.os.Bundle; | |
| import android.support.annotation.Nullable; | |
| import android.support.v4.app.Fragment; | |
| import android.view.LayoutInflater; | |
| import android.view.View; | |
| import android.view.ViewGroup; | |
| import java.lang.ref.WeakReference; | |
| // UI | |
| public class MainFragment extends Fragment { | |
| private Model model; | |
| @Nullable | |
| @Override | |
| public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { | |
| this.model = new Model(); | |
| model.setListener(new ModelListener() { | |
| @Override | |
| public void notify(Model model) { | |
| } | |
| }); | |
| return super.onCreateView(inflater, container, savedInstanceState); | |
| } | |
| } | |
| // Modelと通知用のinterface | |
| interface ModelListener { | |
| void notify(Model model); | |
| } | |
| class Model { | |
| private WeakReference<ModelListener> mListener; | |
| void setListener(ModelListener listener) { | |
| mListener = new WeakReference<>(listener); | |
| } | |
| void doSomething() { | |
| // 何かする | |
| // 本当はnullチェックする | |
| mListener.get().notify(this); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment