2016-06-12 31 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

我知道,但它只記得上次輸入的輸入。並將其作爲變量值。 –

相關問題