This type of question has been asked and answered, but my specific situation returns an empty array. I first create an array in View Controller 1 (VC1). VC1 includes a collection view. I try to add a UIView to the array in cellForItem func.
/// A subclass of `UIViewController` with a `MessagesCollectionView` object
/// that is used to display conversation interfaces.
open class MessagesViewController: UIViewController,
UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
public var cellViewArray = NSMutableArray()
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = messagesCollectionView.dequeueReusableCell(TextMessageCell.self, for: indexPath)
cell.configure(with: message, at: indexPath, and: messagesCollectionView)
let cellView = cell.contentView
//print("cellView = \(cellView)")
messageViewArray.insert(cellView, at: indexPath.row)
//print("messageViewArray = \(String(describing: messageViewArray))")
return cell
}
I confirmed in debug that when the collection view runs, it does save the cellView to messageViewArray and neither are nil.
messageViewArray = (
"<UIView: 0x142913720; frame = (0 0; 359 140); autoresize = W+H; gestureRecognizers = <NSArray: 0x142913d30>; layer = <CALayer: 0x1429138a0>>",
"<UIView: 0x14291bbc0; frame = (0 0; 359 256); autoresize = W+H; gestureRecognizers = <NSArray: 0x14291c1d0>; layer = <CALayer: 0x14291bd40>>",
"<UIView: 0x142929520; frame = (0 0; 359 256); autoresize = W+H; gestureRecognizers = <NSArray: 0x142929b30>; layer = <CALayer: 0x1429296a0>>",
"<UIView: 0x14298e610; frame = (0 0; 359 140); autoresize = W+H; gestureRecognizers = <NSArray: 0x14298ec20>; layer = <CALayer: 0x14298e790>>",
"<UIView: 0x142929520; frame = (0 0; 359 256); autoresize = W+H; gestureRecognizers =
)
In View Controller 2 (VC2), I try to access messageViewArray from VC1 and do something with the UIView objects.
let messagesViewController = MessagesViewController()
print("messagesViewController.messageViewArray = \(messagesViewController.integerViewArray.description)")
This returns the below in debug showing empty array.
messagesViewController.messageViewArray = (
)
Why doesn't the array objects persist in VC2? What change can I make to reference messageViewArray in VC2. Thanks in advance for your time.
This works. You can access it directly. I'm not sure the exact reasoning, so someone else is welcome to explain.
In VC 2 - declare variable.
/// A subclass of `UIViewController` with a `MessagesCollectionView` object
/// that is used to display conversation interfaces.
open class MessagesViewController: UIViewController,
UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
public static var arrayNameInVCTwo : NSMutableArray? = nil
In VC 1 - reference variable from VC 2
let arrayNameInVCOne = MessagesViewController.arrayNameInVCTwo