當我們想要得到一個關鍵值時,我們應該這樣做。爲什麼有默認值參數偏好
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String syncConnPref = sharedPref.getString(SettingsActivity.KEY_PREF_SYNC_CONN, "defVal");
在getString文件中寫道。
/**
* Retrieve a set of String values from the preferences.
*
* <p>Note that you <em>must not</em> modify the set instance returned
* by this call. The consistency of the stored data is not guaranteed
* if you do, nor is your ability to modify the instance at all.
*
* @param key The name of the preference to retrieve.
* **@param defValues Values to return if this preference does not** exist.
*
* @return Returns the preference values if they exist, or defValues.
* Throws ClassCastException if there is a preference with this name
* that is not a Set.
*
* @throws ClassCastException
*/
現在我有一個問題,爲什麼默認值參數必須存在!?
確實事實上,我的問題是。爲什麼android程序員在getString()中做到這一點?這個偏好是否存在與否並不是android檢查的責任。它是應用程序開發人員的責任 – rezachess
最終有人需要進行檢查。幾乎沒有解決它的方法,所以API設計者認爲包含一個提供默認值的方法會很有幫助。首選項是一個很好的用例,因爲99%的時間,*有*爲默認值。 – DeeV
假設您的應用有100種偏好,您認爲哪種方式更易於閱讀? – DeeV