스위프트 4 및 iOS 11을 사용하여 첫 번째 iOS 앱을 마무리하는 데 아주 가깝습니다.NSKeyedArchiver를 사용하여 데이터를 저장하려면 어떻게해야합니까?
이 앱에는 테이블보기 컨트롤러에 표시되는 목록과 편집 가능한 UITextView 개체가있는 상세보기 목록이 있습니다. 내 목표는 사용자가 UITextView의 내용을 편집하고 NSKeyedArchiver를 사용하여 변경 내용을 저장할 수있게하는 것입니다.
목록보기가 완료되었으며 세부 정보보기가 연결되어 있습니다. 편집 할 수는 있지만 저장하지는 않습니다.
입력 내용이 세션 이후에도 지속되지만 편집 내용을 저장하지 않는다는 것을 확인했습니다.
설명서를 검토하고 여러 자습서를 통해 작업 한 결과 통찰력이 필요하지 않았습니다. 나는 상세 뷰의 인터페이스를 보여주기 위해 스크린 샷을 첨부하고 여기에 버튼이 저장 작업을 트리거 저장 상세 뷰 컨트롤러에서 코드 한 : 여기
import UIKit
import os.log
class ViewController: UIViewController, UINavigationControllerDelegate, UITextViewDelegate {
var season: Season?
//MARK: Properties
@IBOutlet weak var seasonDetail: UITextView!
@IBAction func saveButton(_ sender: UIBarButtonItem) {
if let selectedDetail = seasonDetail.text {
seasonDetail.text = selectedDetail
} else {
print("failed to save changes.")
}
saveChanges()
print("Save button clicked")
}
override func viewDidLoad() {
super.viewDidLoad()
title = season?.name
seasonDetail.text = season?.detail
seasonDetail.delegate=self
}
override func viewWillDisappear(_ animated: Bool) {
season?.detail = (seasonDetail?.text)!
}
func textViewDidEndEditing(_ textView: UITextView) {
seasonDetail.text = season?.detail
}
//MARK: UITextViewdDelegate
func textViewShouldReturn(_ textView: UITextView) -> Bool {
textView.resignFirstResponder()
return true
}
func saveChanges() {
print("Saving items to: \(Season.ArchiveURL)")
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(season as Any, toFile: Season.ArchiveURL.path)
if isSuccessfulSave {
os_log("Season sucessfully saved.", log: OSLog.default, type: .debug)
} else {
os_log("Failed to save season.", log: OSLog.default, type: .debug)
}
}
}
데이터 모델 클래스의 코드입니다 :
import UIKit
import os.log
class Season: NSObject, NSCoding {
//MARK: Properties
var name: String
var detail: String
//MARK: Archiving Paths
static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("season")
//MARK: Types
struct PropertyKey {
static let name = "name"
static let detail = "detail"
}
//MARK: Initialization
init?(name: String, detail: String) {
guard !name.isEmpty else {
return nil
}
guard !detail.isEmpty else {
return nil
}
// Initialize stored properties
self.name = name
self.detail = detail
}
//MARK: NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: PropertyKey.name)
aCoder.encode(detail, forKey: PropertyKey.detail)
}
required convenience init?(coder aDecoder: NSCoder) {
// the name is required. If we cannnot get a name string, the initializer should fail.
guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String
else {
os_log("Unable to decode the name for a Season object.", log: OSLog.default, type: .debug)
return nil
}
let detail = aDecoder.decodeObject(forKey: PropertyKey.detail)
self.init(name: name, detail: detail as! String)
}
}
내 목표는 내 코드에없는 것을 이해하고 편집을 포함하여 모든 데이터를 유지하는 방법을 알고있다. 도움이 될만한 방향으로 고맙게 생각합니다.
안녕 VINI는 어떻게 업데이트 된 값을 표시합니까? 감사. – fmz
'seasonDetail.text'를 사용하여 세부 정보를 업데이트했습니다. –
이것이 작동합니까? –