Just a Computer Graphics Studio & My Life

[iOS] 刪除 User Defaults

很多時候我們會把資料儲存在User Defaults,也就是本機端,只要App不被刪掉,那麼每次重新開啟App,就能再從User Defaults取得先前所儲存的資料。

有某時候我們需要把User Defaults給清空,比如要給其它帳號使用,此時登出A就要將A所儲存的User Defaults給清除乾淨,而登入B後又是全新沒有受污染的User Defaults。

該怎麼做呢?以下的code就能刪除所有存在User Defaults中的key,不過卻不會刪掉系統預設的key呢!

/**
 Theme: Delete User Defaults
 IDE: Xcode 7
 Language: Objective C
 Date: 104/12/07
 Author: HappyMan
 Blog: https://cg2010studio.wordpress.com/
 */
#pragma mark - 刪除 UserDefaults
    NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
    NSDictionary *dict = [defs dictionaryRepresentation];
    for (id key in dict) {
        [defs removeObjectForKey:key];
    }
    [defs synchronize];

清空前的User Defaults之key群:

(
GGUserDefaultsKeyLoginAccount,
AppleKeyboardsExpanded,
GGUserDefaultsKeyLoginPassword,
PCSavePendingUserDefaults,
GGUserDefaultsKeyhasFirstShowMenu,
GGUserDefaultsKeyIsLogin,
INNextHearbeatDate,
com.apple.content-rating.ExplicitBooksAllowed,
GGUserDefaultsKeyLoginPasswordAlternative,
AppleKeyboards,
HasUserRegisteredFonts,
PKEnableStockholmSettings,
GGUserDefaultsKeyRememberPassword,
AppleLanguagesDidMigrate,
com.apple.content-rating.TVShowRating,
com.apple.content-rating.ExplicitMusicPodcastsAllowed,
NSLanguages,
com.apple.content-rating.MovieRating,
GGUserDefaultsKeyQBId,
GGUserDefaultsKeyLoginAccountAlternative,
PreferredLanguages,
AddingEmojiKeybordHandled,
MSVLoggingMasterSwitchEnabledKey,
AppleLocale,
AppleLanguages,
NSInterfaceStyle,
com.apple.content-rating.AppRating,
AppleITunesStoreItemKinds
)

清空後的User Defaults之key群:

(
PKEnableStockholmSettings,
INNextHearbeatDate,
MSVLoggingMasterSwitchEnabledKey,
AppleITunesStoreItemKinds,
AddingEmojiKeybordHandled,
com.apple.content-rating.ExplicitBooksAllowed,
com.apple.content-rating.MovieRating,
HasUserRegisteredFonts,
AppleLanguagesDidMigrate,
com.apple.content-rating.AppRating,
AppleLanguages,
NSLanguages,
NSInterfaceStyle,
com.apple.content-rating.ExplicitMusicPodcastsAllowed,
AppleKeyboardsExpanded,
AppleKeyboards,
PreferredLanguages,
AppleLocale,
com.apple.content-rating.TVShowRating
)

key前綴為PC或GG,就是我在此專案中儲存資料用的key喔~

參考:Delete all keys from a NSUserDefaults dictionary iPhone

Advertisements

發表留言

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s

標籤雲

%d 位部落客按了讚: