programing

스위프트 앱에 로컬 데이터를 저장하는 방법은 무엇입니까?

jooyons 2023. 6. 4. 10:29
반응형

스위프트 앱에 로컬 데이터를 저장하는 방법은 무엇입니까?

저는 현재 Swift에서 개발한 iOS 앱을 사용하고 있는데 사용자가 만든 콘텐츠를 기기에 저장해야 하는데 사용자 콘텐츠를 기기에 저장/수신할 수 있는 간단하고 빠른 방법을 찾을 수 없는 것 같습니다.

로컬 스토리지를 저장하고 액세스하는 방법을 설명해 주시겠습니까?

이 아이디어는 사용자가 작업을 실행할 때 데이터를 저장하고 앱이 시작될 때 데이터를 수신하는 것입니다.

몇 개의 문자열이나 공통 유형을 저장하는 가장 간단한 솔루션은 UserDefaults입니다.

UserDefaults 클래스는 float, double, 정수, 부울 값 및 URL과 같은 일반적인 유형에 액세스할 수 있는 편리한 방법을 제공합니다.

UserDefaults원하는 키와 비교하여 개체를 저장할 수 있습니다. 이러한 키는 재사용할 수 있도록 액세스할 수 있는 위치에 저장하는 것이 좋습니다.

열쇠들.

struct DefaultsKeys {
    static let keyOne = "firstStringKey"
    static let keyTwo = "secondStringKey"
}

설정

let defaults = UserDefaults.standard
defaults.set("Some String Value", forKey: DefaultsKeys.keyOne)
defaults.set("Another String Value", forKey: DefaultsKeys.keyTwo)

점점 ~하다

let defaults = UserDefaults.standard
if let stringOne = defaults.string(forKey: DefaultsKeys.keyOne) {
    print(stringOne) // Some String Value
}
if let stringTwo = defaults.string(forKey: DefaultsKeys.keyTwo) {
    print(stringTwo) // Another String Value
}

스위프트 2.0

2 스위프트 2.0에서UserDefaults라고 불렸습니다.NSUserDefaults그리고 세터와 게터의 이름은 약간 다릅니다.

설정

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("Some String Value", forKey: DefaultsKeys.keyOne)
defaults.setObject("Another String Value", forKey: DefaultsKeys.keyTwo)

점점 ~하다

let defaults = NSUserDefaults.standardUserDefaults()
if let stringOne = defaults.stringForKey(DefaultsKeys.keyOne) {
    print(stringOne) // Some String Value
}
if let stringTwo = defaults.stringForKey(DefaultsKeys.keyTwo) {
    print(stringTwo) // Another String Value
}

보조 구성보다 심각한 경우 보다 강력한 영구 저장소를 사용하는 것을 고려해야 합니다.

그들은 NSUser Defaults를 사용한다고 말합니다.

처음으로 장기(앱 종료 후) 데이터 스토리지를 구현할 때 온라인에서 읽은 모든 내용이 NSUserDefaults를 가리켰습니다.하지만, 저는 사전을 보관하고 싶었고, 가능하긴 했지만, 그것은 고통으로 판명되었습니다.저는 타이프 오류를 없애려고 몇 시간을 보냈습니다.

NSUserDefaults 기능도 제한됩니다.

NSUserDefaults의 읽기/쓰기가 실제로 앱이 모든 것을 읽거나 전혀 쓰지 않도록 강제하는 방식을 자세히 읽어보니 효율적이지 않습니다.어레이를 검색하는 것이 간단하지 않다는 것을 알게 되었습니다.몇 개 이상의 문자열이나 부울을 저장하는 경우 NSUserDefaults는 적합하지 않다는 것을 깨달았습니다.

또한 확장할 수 없습니다.코딩하는 방법을 배우고 있다면 확장 가능한 방법을 배우십시오.환경설정과 관련된 단순 문자열 또는 부울을 저장하는 경우에만 NSUserDefaults를 사용하십시오.코어 데이터를 사용하여 어레이 및 기타 데이터를 저장하는 것은 그들이 말하는 것만큼 어렵지 않습니다.작게 시작하세요.

업데이트: 또한 Apple Watch 지원을 추가하면 다른 잠재적 고려 사항이 있습니다.이제 앱의 NSUserDefaults가 자동으로 Watch Extension으로 전송됩니다.

핵심 데이터 사용

그래서 저는 코어 데이터가 더 어려운 해결책이라는 경고를 무시하고 읽기 시작했습니다.3시간 안에 저는 그것을 작동시켰습니다.앱을 열 때 테이블 배열을 코어 데이터에 저장하고 데이터를 다시 로드했습니다!튜토리얼 코드는 쉽게 적응할 수 있었고 약간의 추가 실험만으로 제목과 세부 배열을 모두 저장할 수 있었습니다.

따라서 NSUserDefault 유형 문제로 어려움을 겪고 있거나 문자열 저장 이상이 필요한 사람이라면 이 게시물을 읽는 데 한 시간 또는 두 시간을 할애하여 핵심 데이터를 사용하는 것을 고려해 보십시오.

제가 읽은 튜토리얼은 다음과 같습니다.

http://www.raywenderlich.com/85578/first-core-data-app-using-swift

"핵심 데이터"를 선택하지 않은 경우

앱을 만들 때 "핵심 데이터"를 선택하지 않은 경우 앱을 추가할 수 있으며 5분만 소요됩니다.

http://craig24.com/2014/12/how-to-add-core-data-to-an-existing-swift-project-in-xcode/

http://blog.zeityer.com/post/119012600864/adding-core-data-to-an-existing-swift-project

핵심 데이터 목록에서 삭제하는 방법

Coredata Swift에서 데이터 삭제

@bploat과 http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/ 링크 덕분에 좋습니다.

기본적인 문자열 스토리지에 대한 답은 매우 간단합니다.

let defaults = NSUserDefaults.standardUserDefaults()

// Store
defaults.setObject("theGreatestName", forKey: "username")

// Receive
if let name = defaults.stringForKey("username")
{
    print(name)
    // Will output "theGreatestName"
}

여기에 요약했습니다. http://ridewing.se/blog/save-local-data-in-swift/

NSCodingNSKidedArchiver를 사용하는 것은 너무 복잡한 데이터에 대한 또 다른 좋은 옵션입니다.NSUserDefaults하지만 코어 데이터는 과잉 살상이 될 수 있습니다.또한 파일 구조를 보다 명확하게 관리할 수 있는 기회를 제공하므로 암호화를 사용하려는 경우 유용합니다.

Swift 4.0의 경우 다음과 같이 쉬워졌습니다.

let defaults = UserDefaults.standard
//Set
defaults.set(passwordTextField.text, forKey: "Password")
//Get
let myPassword = defaults.string(forKey: "Password")

스위프트 5+

기본 내장 로컬 스토리지 기능에 대해 자세히 설명하는 답변은 없습니다.그것은 현악기 이상의 것을 할 수 있습니다.

기본값에서 데이터를 '얻기' 위해 Apple 설명서에서 직접 다음과 같은 옵션을 사용할 수 있습니다.

func object(forKey: String) -> Any?
//Returns the object associated with the specified key.

func url(forKey: String) -> URL?
//Returns the URL associated with the specified key.

func array(forKey: String) -> [Any]?
//Returns the array associated with the specified key.

func dictionary(forKey: String) -> [String : Any]?
//Returns the dictionary object associated with the specified key.

func string(forKey: String) -> String?
//Returns the string associated with the specified key.

func stringArray(forKey: String) -> [String]?
//Returns the array of strings associated with the specified key.

func data(forKey: String) -> Data?
//Returns the data object associated with the specified key.

func bool(forKey: String) -> Bool
//Returns the Boolean value associated with the specified key.

func integer(forKey: String) -> Int
//Returns the integer value associated with the specified key.

func float(forKey: String) -> Float
//Returns the float value associated with the specified key.

func double(forKey: String) -> Double
//Returns the double value associated with the specified key.

func dictionaryRepresentation() -> [String : Any]
//Returns a dictionary that contains a union of all key-value pairs in the domains in the search list.

다음은 '설정' 옵션입니다.

func set(Any?, forKey: String)
//Sets the value of the specified default key.

func set(Float, forKey: String)
//Sets the value of the specified default key to the specified float value.

func set(Double, forKey: String)
//Sets the value of the specified default key to the double value.

func set(Int, forKey: String)
//Sets the value of the specified default key to the specified integer value.

func set(Bool, forKey: String)
//Sets the value of the specified default key to the specified Boolean value.

func set(URL?, forKey: String)
//Sets the value of the specified default key to the specified URL.

대용량 데이터 세트가 아닌 기본 설정과 같은 것을 저장하는 경우 이러한 옵션은 완벽하게 좋습니다.

이중 예:

설정:

let defaults = UserDefaults.standard
var someDouble:Double = 0.5
defaults.set(someDouble, forKey: "someDouble")

가져오기:

let defaults = UserDefaults.standard
var someDouble:Double = 0.0
someDouble = defaults.double(forKey: "someDouble")

게터 중 하나에 대한 흥미로운 은 사전 표현입니다. 이 편리한 게터는 데이터 유형이 무엇이든 상관없이 모든 데이터 유형을 가져와서 문자열 이름으로 액세스할 수 있는 좋은 사전에 저장하고 'any' 유형이므로 다시 요청할 때 해당하는 올바른 데이터 유형을 제공합니다.

여러분은 자클및개저수장있도다습니할체를래사를 하여 .func set(Any?, forKey: String)그리고.func object(forKey: String) -> Any?그에 따라 세터와 게터.

이를 통해 로컬 데이터를 저장하는 UserDefaults 클래스의 성능이 더욱 향상되기를 바랍니다.

얼마나 저장해야 하는지, 얼마나 자주 저장해야 하는지에 대한 메모에 Hardy_Germany는 이 게시물에서 좋은 답변을 했습니다. 여기 인용문이 있습니다.

이미 언급한 바와 같이:.plist(예: UserDefaults)에 데이터를 저장하기 위한 SIZE 제한(물리적 메모리 제외)을 알지 못합니다.그래서 그것은 얼마나 많은지의 문제가 아닙니다.

진짜 문제는 얼마나 자주 새 값을 쓰느냐 하는 것입니다.이는 이 쓰기로 인해 발생하는 배터리 소모와 관련이 있습니다.

IOS는 데이터 무결성을 유지하기 위해 단일 값이 변경된 경우 "디스크"에 물리적 쓰기를 피할 수 없습니다.UserDefaults의 경우 전체 파일이 디스크로 다시 작성됩니다.

이렇게 하면 "디스크"에 전원이 공급되고 더 오랜 시간 동안 전원이 켜진 상태로 유지되며 IOS가 저전력 상태로 전환되는 것을 방지할 수 있습니다.

게시물에서 사용자 Mohammad Reza Farahani가 언급한 또 다른 주목할 점은 userDefaults의 비동기적이고 동기적인 특성입니다.

기본값을 설정하면 프로세스 내에서 동기적으로 변경되며 영구 스토리지 및 기타 프로세스에서는 비동기적으로 변경됩니다.

예를 들어 프로그램을 저장하고 빨리 닫으면 비동기식으로 지속되기 때문에 결과가 저장되지 않을 수 있습니다.프로그램을 종료하기 전에 저장할 계획이라면 완료할 시간을 줌으로써 이 문제를 설명할 수 있습니다.

이에 대한 좋은 해결책을 댓글로 공유할 수 있는 사람이 있을까요?

스위프트 3.0

세터 : 로컬 스토리지

let authtoken = "12345"
    // Userdefaults helps to store session data locally 
 let defaults = UserDefaults.standard                                           
defaults.set(authtoken, forKey: "authtoken")

 defaults.synchronize()

Getter: 로컬 스토리지

 if UserDefaults.standard.string(forKey: "authtoken") != nil {

//perform your task on success }

스위프트 3용

UserDefaults.standard.setValue(token, forKey: "user_auth_token")
print("\(UserDefaults.standard.value(forKey: "user_auth_token")!)")

어떤 이유로 인해 사용자 기본값을 처리하지 않으려는 사용자를 위해 NSKedArchiver 및 NSKedUnarchiver라는 다른 옵션이 있습니다.아카이브 서버를 사용하여 개체를 파일에 저장하고 아카이브된 파일을 원래 개체에 로드하는 데 도움이 됩니다.

// To archive object,
let mutableData: NSMutableData = NSMutableData()
let archiver: NSKeyedArchiver = NSKeyedArchiver(forWritingWith: mutableData)
archiver.encode(object, forKey: key)
archiver.finishEncoding()
return mutableData.write(toFile: path, atomically: true)

// To unarchive objects,
if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
    let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
    let object = unarchiver.decodeObject(forKey: key)
}

위의 샘플 코드를 사용하여 로컬 저장소에 객체를 저장/로드하는 간단한 유틸리티를 작성했습니다.이거 보고 싶으실 거예요.https://github.com/DragonCherry/LocalStorage

이것은 Swift 5에서 이를 수행하는 방법에 대한 훌륭한 설명입니다. https://www.hackingwithswift.com/example-code/system/how-to-save-user-settings-using-userdefaults

요약:.

값을 설정하는 방법

let defaults = UserDefaults.standard
defaults.set("value", forKey: "key")

문자열 값을 가져오는 방법

let key = defaults.object(forKey: "StringKey") as? [String] ?? [String]()

정수 값을 가져오는 방법

let key = defaults.integer(forKey: "IntegerKey")

NsUserDefaults는 작은 변수 크기만 저장합니다.객체를 많이 저장하고 싶다면 CoreData를 네이티브 솔루션으로 사용하거나 객체를 .save() 함수처럼 쉽게 저장할 수 있는 라이브러리를 만들었습니다.SQLite를 기반으로 합니다.

선디큐라이트

확인하시고 의견을 말씀해주세요.

저는 이 답을 찾았고 데이터를 저장할 수 있었지만 Swift 4.1 이후로 앱 스토리지를 사용하는 훨씬 더 쉬운 방법이 있었습니다.

@AppStorage("studentNames") var studentName: String = "Put name here"

각 항목은 고유해야 하지만 문자열을 사용하면 여기에 다양한 데이터를 저장할 수 있습니다.

이를 위해 비디오 튜토리얼을 만들었습니다. http://youtube.com/watch?v=nLsJD6yL9Ps

언급URL : https://stackoverflow.com/questions/28628225/how-to-save-local-data-in-a-swift-app

반응형