【问题标题】:Why I am getting nil while unwrapping an Optional value when I eliminated all nil_s?当我消除所有 nil_s 时,为什么我在展开 Optional 值时得到 nil?
【发布时间】:2016-06-11 12:59:06
【问题描述】:

嘿,我在放置变量时遇到问题。 我如何使用我使用的变量,让我们在另一个函数“B”中的函数“A”中说。换句话说,在函数“B”中使用函数“A”中的变量

我有函数(“A”)来设置通知文本:

let sentence = textField.text! + " Some beautiful text!"

let firstWord = sentence.characters.split(" ").first.map(String.init)

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

现在我必须在该变量中的另一个函数(“B”)中调用firstWord

let predicate = CNContact.predicateForContactsMatchingName(firstWord)

我尝试在ViewDidLoad 和课外添加这些第一个变量sentencefirstWord,但一无所获。我不断收到错误"found nil while unwrapping" 当用户像这样点击通知操作按钮时,我调用变量predicate的函数。

NSNotificationCenter.defaultCenter().addObserver(self, selector: "functionWhereIsPredicateVariable:", name: IDENTIFICATOR, object: nil)

我必须将firstWord 存储到NSUserDefaults 还是必须以其他方式进行??

【问题讨论】:

  • 查看textField的outlet
  • 我有点困惑...你能尝试更详细地解释一下吗?谢谢

标签: ios swift global-variables


【解决方案1】:

您可以将您的姓名保存到用户信息中

let userInfo = ["url" : "Hello","name":nameField.text!]

//Set notification
                LocalNotificationHelper.sharedInstance().scheduleNotificationWithKey("TempCo", title: "see options(left)", message:nameField.text!+" Your contact needs to be deleted!", date: deadlinePicker.date, userInfo: userInfo)

然后你可以从通知的对象中获取它并发布它。

func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {
    if identifier == DELETECONTACT {
        print("delete action - tapped")

        NSNotificationCenter.defaultCenter().postNotificationName(DELETECONTACT, object:notification.userInfo)

你可以从通知的对象中获取名字

//**DELETE CONTACT FUNCTION**\\
func contactDelete(notification : NSNotification){
let name:String? = notification.object?["name"]  as? String

【讨论】:

  • 如果我尝试从通知对象中获取名称,我会在展开时得到 nil。但如果我让它工作,这绝对是最好的解决方案
  • 你应该确保你已经正确设置了 UILocalNotification 的 userInfo
  • 我尝试使用您刚刚设置的完全相同的用户信息。嗯..我是否也必须创建单独的 userInfo 数组?我也尝试打印 userInfo ,它也给了我 nil 。
  • 从您的演示中看到,您没有准确设置用户信息。
【解决方案2】:

您有两组具有相同名称的变量,一组在类范围内声明,另一组在函数范围内声明。在函数 A 中,您正在设置函数范围变量的值,但在函数 B 中,您正在访问仍然为 nil 的类范围变量。

要解决这个问题,请去掉函数 A 中使用句子和 firstWord 的“let”。

【讨论】:

  • 我做到了,但我还是得到了零。我用更多细节编辑了我的问题。我确实明白如果它具有值甚至控制台向我显示可选值,它是如何为零的。在代码中找到自己的错误怎么这么难:D
  • 我说过要删除 let in 函数 A,在你的问题中它仍然存在。使用最新的完整代码更新您的问题。
  • 做到了。我什至测试了我的数组是否在函数“B”中包含“firstWord”并且它确实包含它,但它不会删除给定的 firstName。它只是将最后输入的“firstName”保留为变量
  • 这个问题只是一团糟-发布的代码试图成为链接到的整个代码的摘要,只会让人感到困惑。不要那样做。如果您要链接整个代码,那么在问题中提及代码中的实际名称,例如在任何地方都没有名为 myArrayWhereIKeepValuesToDelete 的此类数组。解决问题,否则没有人可以或将回答它。无论如何,您似乎重复了我已经指出过一次的相同错误 - 您有两个同名变量:firstWordAsString。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多