本文介绍了快速从NSDictionary读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在使用此代码从NSDictionary中读取数据:

I am using this code to read data from NSDictionary:

let itemsArray: NSArray = response.objectForKey("items") as! NSArray;
let nextPageToken: String = response.objectForKey("nextPageToken") as! String

var videoIdArray: [String] = []

for (item) in itemsArray {
      let videoId: String? = item.valueForKey("id")!.valueForKey("videoId") as? String
      videoIdArray.append(videoId!)
}

但是当我itemsnextPageToken不存在时,会出现此错误:

But when i items or nextPageToken are not exist i get this error:

fatal error: unexpectedly found nil while unwrapping an Optional value

知道为什么吗?我该如何解决?

Any idea why? how i can fix it?

推荐答案

您的代码中存在两个问题:

There are two issues in your code:

  1. 您正试图强制拆开一个可以为nil的可选内容.如果不确定数据是否可用,切勿使用强制展开.
  2. 您正在使用valueForKey:而不是objectForKey:从词典中检索数据.使用 objectForKey:而不是valueForKey:从字典中获取数据.
  1. You are trying to force unwrap an optional that can be nil. Never use forced unwrapping, if you are not sure whether the data will be available or not.
  2. You are using valueForKey: instead of objectForKey: for retrieving data from a dictionary. Use objectForKey: instead of valueForKey: for getting data from a dictionary.

您可以通过以下方式解决崩溃问题:

You can fix the crash by:

let itemsArray: NSArray?   = response.objectForKey("items") as? NSArray;
let nextPageToken: String? = response.objectForKey("nextPageToken") as? String

var videoIdArray: [String] = []
if let itemsArray = itemsArray
{
    for (item) in itemsArray
    {
       let videoId: String? = item.objectForKey("id")?.objectForKey("videoId") as? String
       if (videoId != nil)
       {
          videoIdArray.append(videoId!)
       }
     }
}

这篇关于快速从NSDictionary读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-09 02:23
查看更多