2017-02-05 6 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

관련 문제