2016-06-12 29 views
0

第二次点击按钮时我再也没有价值了。如何在每个应用程序加载时加载变量。我谈论的变量正在改变,因为它总是textField.text!,它是用户输入。我用它当用户点击LocalNotification动作,应用程序打开,然后函数触发这样的:将TextField作为应用程序启动时的变量粘贴到LocalNotification

NSNotificationCenter.defaultCenter().addObserver(self, selector: "someFunctionWhereIsMyProblematicVariableINeedToLoad:", name: IDENTIFIER, object: nil) 

如何坚持每次用户进入它,进入本地通知变量。是否每个通知都有所不同或仅仅是文本更改?是否有任何ID使每个通知都特殊?

LocalNotificationHelper.sharedInstance().scheduleNotificationWithKey("someText", title: "see options(left)", message:textField.text!+"someText", date: deadlinePicker.date, userInfo: userInfo) 

我需要textField.text要在这个变量:let predicate = CNContact.predicateForContactsMatchingName(textField.text!)

我试图将它们存储到NSUserDefaults,进入阵列和循环通过arrays找到,如果值存在等,但它的工作原理只是第一次第二次它是nil

编辑:它只保留最后输入的值作为变量。如何让他们全部?

在这里,我向您展示的图片是我试图用语言来解释:

enter image description here

现在,如果蓝色按钮被窃听我启动功能,我需要用“firstTimeEntered”为变量,但在第二通知它是 “SecondTimeEntered”

变量类范围:

var sentence:String = "" 
var firstWord = [String]() 
var firstWordAsString:String = "" 

功能 “A”:

  sentence = textField.text! + " needs to be deleted from array." 
      var firstWordAsString = sentence.characters.split(" ").first.map(String.init) 
      firstWord.append(firstWordAsString!) 
      defaults.setObject(firstWord, forKey: "firstWord") 

      let userInfo = ["url" : "Hello"] 

      //Set notification 
      LocalNotificationHelper.sharedInstance().scheduleNotificationWithKey("someText", title: "see options(left)", message: sentence, date: deadlinePicker.date, userInfo: userInfo) 

函数 “B”:

defaults.objectForKey("firstWord") as? String 

     if contacts.contains(firstWordAsString){ 

     let predicate = CNContact.predicateForContactsMatchingName(firstWordAsString) 

回答

1

这是最终的范围的问题。

//This is the largest scope called the global scope. anything available here is available anywhere in your application. 
class myclass { 
    //this is the class level scope any variables here would be available from within the class but not outside of it. I can use any variables in the class scope or the global scope. 
    func myFunction() { 
     //this is the function scope, any variables here would be available from within the function but not outside of this function. I can use any variables in the class scope, global scope and my own scope. 
    } 

    func mySecondFunction() { 
     //this is also the function scope, I can have my own variables but I cannot see the variables in myFunction() 
    } 

所以,如果你把一个var savedValues = [String]()在功能上它不会从另一个功能。但是如果你把它放在类范围中,它将在两个函数中都可用。每次函数启动时,它都会定义函数变量,当函数变量自身退出时,变量将从内存中移除。

解决你的问题在你的类中放入一串字符串,然后使用该类级数组的append方法向它添加新的东西。然后你可以使用过滤方法或者通过循环来搜索该数组。

+0

Masen,然后我怎么才能搜索到我刚刚从通知中得到的那个词,并将它从数组中删除?我试过这样:如果contacts.contains(firstWord)(我不能这样做,因为它是在数组中)。然后从数组中删除它。 –

+0

对于数组,没有'.remove(object)'方法,而是依赖于'removeAtIndex(index)'方法。你需要找到一个对象的索引,然后调用它。 '如果让我找到= array.indexOf(searchTerm){array.removeAtIndex(found)}'可能会做的伎俩。 –

+0

我知道,但它只记得上次输入的输入。并将其作为变量值。 –

相关问题