我想在一个let中保存两个文本域文本。我需要这个,所以我可以同时上传数据,否则它将产生2个单独的数据。 newStoryYoutube
和newStorynaam
需要一个let。这是我的代码:
@IBAction func postDidTouch(_ sender: UIBarButtonItem)
{
if Youtubelink.text != "" {
// Create and save a new story
let newStoryYoutube = Story(text: Youtubelink.text!)
newStoryYoutube.save()
}
if Naamgeluidje.text != "" {
// Create and save a new story
let newStorynaam = Story(textnaam: Naamgeluidje.text!)
newStorynaam.save()
self.navigationController!.popViewController(animated: true)
}
}
另一个viewcontroller中的Story类:
class Story
{
var text: String = ""
var textnaam: String = ""
var numberOfLikes = 0
var numberOfAngry = 0
let ref: DatabaseReference!
init(text: String) {
self.text = text
ref = Database.database().reference().child("stories").childByAutoId()
}
init(textnaam: String) {
self.textnaam = textnaam
ref = Database.database().reference().child("stories").childByAutoId()
}
init(snapshot: DataSnapshot)
{
ref = snapshot.ref
if let value = snapshot.value as? [String : Any] {
text = value["text"] as! String
textnaam = value["textnaam"] as! String
numberOfLikes = value["numberOfLikes"] as! Int
numberOfAngry = value["numberOfAngry"] as! Int
}
}
func save() {
ref.setValue(toDictionary())
}
func toDictionary() -> [String : Any]
{
return [
"text" : text,
"textnaam" : textnaam,
"numberOfLikes" : numberOfLikes,
"numberOfAngry" : numberOfAngry
]
}
}
答案 0 :(得分:0)
您正在此处创建Story类的两个实例。你应该做的是创建一个没有任何参数的构造函数,然后初始化你的类一次,然后设置如下的属性。
let newStory = Story()
@IBAction func postDidTouch(_ sender: UIBarButtonItem)
{
if Youtubelink.text != "" {
// Create and save a new story
newStory.text = Youtubelink.text!
newStory.save()
}
if Naamgeluidje.text != "" {
// Create and save a new story
newStory.textnaam = Naamgeluidje.text!
newStory.save()
self.navigationController!.popViewController(animated: true)
}
}
将您的Story类更改为此类,以便您可以初始化它而不传递任何参数
class Story
{
var text: String = ""
var textnaam: String = ""
var numberOfLikes = 0
var numberOfAngry = 0
let ref: DatabaseReference!
init(text: String) {
self.text = text
ref = Database.database().reference().child("stories").childByAutoId()
}
init(textnaam: String) {
self.textnaam = textnaam
ref = Database.database().reference().child("stories").childByAutoId()
}
init() {
ref = Database.database().reference().child("stories").childByAutoId()
}
init(snapshot: DataSnapshot)
{
ref = snapshot.ref
if let value = snapshot.value as? [String : Any] {
text = value["text"] as! String
textnaam = value["textnaam"] as! String
numberOfLikes = value["numberOfLikes"] as! Int
numberOfAngry = value["numberOfAngry"] as! Int
}
}
func save() {
ref.setValue(toDictionary())
}
func toDictionary() -> [String : Any]
{
return [
"text" : text,
"textnaam" : textnaam,
"numberOfLikes" : numberOfLikes,
"numberOfAngry" : numberOfAngry
]
}
}