Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 为什么词典是零?_Ios_Swift - Fatal编程技术网

Ios 为什么词典是零?

Ios 为什么词典是零?,ios,swift,Ios,Swift,我正在将所选单元格的标签和图像传递到下一个视图,但当我打印NSDictionary时,我得到的是一个零。为什么? func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { print("Cell \(indexPath.row) selected") print(arrayOfFriendsNames[indexPath.

我正在将所选单元格的标签和图像传递到下一个视图,但当我打印NSDictionary时,我得到的是一个零。为什么?

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    print("Cell \(indexPath.row) selected")
    print(arrayOfFriendsNames[indexPath.row])
     self.dicSelected = ["friendname" : arrayOfFriendsNames[indexPath.row], "friendimage" :  arrayOfFriends[indexPath.row]]
    self.performSegueWithIdentifier("friendaccess", sender: dicSelected)
}

  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if(segue.identifier == "friendaccess"){

        let nextViewOBJ = segue.destinationViewController as! FriendProfilePages

        //let data = sender as! NSDictionary
        //nextViewOBJ.dicData = data
        nextViewOBJ.dicData = self.dicSelected;

    }
}
下面是FriendProfilePages的代码

var friendname = UILabel()
var friendimage = UIImageView()

 var dicData : NSDictionary = NSDictionary()


 override func viewWillAppear(animated: Bool) {
    print("Dictionary: \(self.dicData)")
}
viewDidLoad太早,无法访问prepareForSegue中的属性集。顾名思义,此方法在加载视图控制器时调用

在prepareForSegue中,您可以从segue访问destinationViewController属性,因此视图控制器已经加载,viewDidLoad已经执行


您可以在VIEW中访问字典,它将显示为:动画:或者,更好的做法是,在dicData上定义一个setter函数,在设置dictionary属性时执行任何必要的任务。

只是为了强调Paulw11所陈述的内容和一些上下文:

您应该注意的是,在prepareForSegue中,不能保证IBOutlets为非零。这意味着在实践中,大多数情况下无法可靠地设置对象。相反,您应该在目标视图控制器上创建数据变量,然后设置数据的值。您当前正在做的是设置对象的值,而不是传递数据

您试图传递的词典是否有任何有效内容也不清楚。在将字典传递给目标之前,可以尝试在源代码视图控制器的类级别设置字典。完成此操作后,可以尝试在将数据发送到目标视图控制器之前,使用断点评估源上字典中的数据。您可以进一步跟踪目标中的数据,以确保在开始使用它之前它仍然有效

要解决此问题,请执行以下操作:

在FriendProfilePages类中:

定义用于保存字典的变量:

var dicData:Dictionary? = nil
然后在prepareForSegue方法中:

//initialize your Dictionary with some data before you assign it
... 
//(I don't know how you are creating the Dictionary but your code above does not show a proper initialization).

//set the data value on the target view controller
nextViewOBJ.dicData = self.dicSelected 
//above only works if you have a valid Dictionary

然后,在目标视图控制器中,只需在使用字典之前添加断点,并确认字典包含正确的数据。

什么是NSDictionary nil?如何执行setter函数?setter和getter在iBooks上的Swift手册中有描述。您还应在集合视图中使用indexath.item而不是indexath.row