2016-12-15 6 views
0

Как сохранить и удалить 2 текстовых файла с помощью Realm?Как сохранить и удалить 2 текстовых файла в Realm?

Ниже мой код:

class ViewController: UIViewController , UITableViewDataSource , UITableViewDelegate { 
    @IBOutlet weak var text1: UITextField! 
    @IBOutlet weak var text2: UITextField! 
    @IBOutlet weak var ttableview: UITableView! 

    //delete row and tableview and array 
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
     if editingStyle == .delete { 
      array1.remove(at: indexPath.row) 
      array2.remove(at: indexPath.row) 
      ttableview.deleteRows(at: [indexPath], with: .fade) 
     } 
    } 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return array1.count 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = ttableview.dequeueReusableCell(withIdentifier: "cell") as! Cell 
     cell.lable1.text = array1[indexPath.row] 
     cell.lable2.text = array2[indexPath.row] 
     return cell 
    } 

    var array1 = [String]() 
    var array2 = [String]() 
} 

Я хочу, чтобы сохранить и удалить мои 2 текстовых полей в виде таблицы.

enter image description here

Ниже приведен код, чтобы добавить его в Tableview

@IBAction func Add(_ sender: Any) { 
    array1.insert(text1.text!, at: 0) 
    array2.insert(text2.text!, at: 0) 
    self.ttableview.reloadData() 
} 

func queryPeople(){ 
    let realm = try! Realm() 
    let allPeople = realm.objects(CCat.self) 
    for person in allPeople { 
     print("\(person.name) to \(person.job)") 
    } 
} 
+0

Просьба указать, к какому вопросу вы столкнулись в этом коде, а также добавить описание. –

+0

как использовать область здесь я хочу сохранить данные в delete, я хочу код, вы можете мне помочь? –

ответ

0

Вы должны прочитать документацию Realm в первую очередь. https://realm.io/docs/swift/latest/

Чтобы сохранить объект в Realm, определите класс модели как подкласс Object.

class Person: Object { 
    // Optional string property, defaulting to nil 
    dynamic var name: String? = nil 

    // Optional int property, defaulting to nil 
    // RealmOptional properties should always be declared with `let`, 
    // as assigning to them directly will not work as desired 
    let age = RealmOptional<Int>() 
} 

Затем создайте экземпляр класса модели.

let author = Person() 
author.name = "David Foster Wallace" 

Создать экземпляр Realm.

// Get the default Realm 
let realm = try! Realm() 
// You only need to do this once (per thread) 

Начните транзакцию и добавьте объект в Царство.

// Add to the Realm inside a transaction 
try! realm.write { 
    realm.add(author) 
}