2017-02-05 5 views
1

私はゆっくりとオブジェクトの範囲をよりよく把握していますし、それらをアプリ内でどうやって渡すこともできます。 Breadcrumbsサンプルプロジェクトは、NSUserDefaultsを使用して設定を保存します。アプリケーションデリゲートのコードとオンラインドキュメントから、メソッドwillFinishLaunchingWithOptionsが実行されるたびにdefaultsDictionary変数がインスタンス化されていることがわかりました。したがって、サンプルプロジェクトを開くたびに設定を変更した場合、willFinishLaunchingWithOptionsメソッドによって設定がオーバーライドされると想定しています。私はこの前提を訂正し、設定が常にwillFinishLaunchingWithOptionsで提供されるデフォルト値にリセットされると自信を持って言えますか?ここで次のコードでは、アプリケーションを開くたびにNSUserDefaultsの設定がリセットされていますか?

はサンプルコードです:

import UIKit 
import MapKit // for MKUserTrackingModeNone 

@objc(BreadcrumbAppDelegate) 
@UIApplicationMain 
class BreadcrumbAppDelegate: NSObject, UIApplicationDelegate { 

    // The app delegate must implement the window @property 
    // from UIApplicationDelegate @protocol to use a main storyboard file. 
    var window: UIWindow? 

    func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { 
     // it is important to registerDefaults as soon as possible, 
     // because it can change so much of how your app behaves 
     // 
     var defaultsDictionary: [String : AnyObject] = [:] 

     // by default we track the user location while in the background 
     defaultsDictionary[TrackLocationInBackgroundPrefsKey] = true as NSNumber 

     // by default we use the best accuracy setting (kCLLocationAccuracyBest) 
     defaultsDictionary[LocationTrackingAccuracyPrefsKey] = kCLLocationAccuracyBest as NSNumber 

     // by default we play a sound in the background to signify a location change 
     defaultsDictionary[PlaySoundOnLocationUpdatePrefsKey] = true as NSNumber 

     UserDefaults.standard.register(defaults: defaultsDictionary) 

     //print(defaultsDictionary) 
     //dump(defaultsDictionary) 

     return true 
    } 

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { 
     //.. 
     return true 
    } 

} 

私は私の仮定が間違っていると言いたいが、私はwillFinishLaunchingWithOptionsメソッドは、ユーザーがアプリを開く次の時間をスキップする方法の精神的な接続をしていませんよしたがって、設定をリセットしません。私が読んだことに基づいて、willFinishLaunchingWithOptionsメソッドが毎回実行時環境によって自動的に起動されると仮定します。私がまだ学んでいるので、どんな情報も非常に高く評価されます。

+1

私はあなたにいくつかのサンプルコードを与えました**これはあなたがしたいことをしない**別の理由**、私の答えが助けてくれたら教えてください! – owlswipe

答えて

1

あなたの前提は正しくありません。 UserDefaults register(defaults:)は、特定のキーに明示的な値が保存されていない場合、単にUserDefaultsから値を取得する方法です。

最初は、UserDefaultsは空です。キーの値を取得しようとすると、nilが返されます。キーの値を明示的に保存すると、そのキーの値を取得すると、もちろん保存された値が得られます。

register(defaults:)を使用すると、その動作の一部が変更されます。キーの値を読み込もうとしていて現在値が存在しない場合は、UserDefaultsはキーの登録されているデフォルト値があればそれを返して返します。鍵のデフォルトが登録されていない場合は、nilとなります。

register(defaults:)は値をリセットしません。値を置き換えるものではありません。存在しない値を読み込む際のメモリ内のフォールバックとしてのみ存在します。

+2

最も重要なことに、 'register'はディスク上のUserDefaultsプロパティリストに_書き込みしません。 – matt

関連する問題