append to array from different class in swift

Im trying to append to my array

var feedArray: [AnyObject] = []

from another class.
I have 2 classes:

  • NSMutableArray - Add array at start
  • Appending text to NSTextView in Swift 3
  • UIBezierPath appending overlapping isn't filled
  • How to append string in local resource txt file for iOS sdk
  • Appending to an empty array giving error
  • Swift: Appending to Dictionary
  • class FeedViewController: UIViewController, UICollectionViewDataSource,
         UICollectionViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
          var feedArray: [AnyObject] = []
    

    and

    class AddEditViewController: UIViewController, NSFetchedResultsControllerDelegate,
          UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    

    I want to in my “AddEditViewController” append the array “feedArray”.
    But I’m not able.
    I have tried:

    FeedViewController().feedArray.append("TheObjectImTryingToAdd")
    

    I even tried to put

    print(FeedViewController().feedArray.count)
    

    but the result is always 0 even though the array have 3 objects.

    what I’m i doing wrong? if you want to see detailed code, this is my previous question: why won't my main viewcontroller update when i segue back?

    Solutions Collect From Internet About “append to array from different class in swift”

    So, After playing around a little bit and trying to learn, I found the solution

    First of all, add the array outside of the class so it is global, so instead of:

    import UIKit
    import CoreData
    import MobileCoreServices
    
    class FeedViewController: UIViewController, UICollectionViewDataSource,
    UICollectionViewDelegate, UIImagePickerControllerDelegate,
    UINavigationControllerDelegate {
    
       @IBOutlet weak var collectionView: UICollectionView!
       var feedArray: [AnyObject] = []
    

    change it so you have:

    import UIKit
    import CoreData
    import MobileCoreServices
    
     var feedArray: [AnyObject] = []
    
    class FeedViewController: UIViewController, UICollectionViewDataSource,
    UICollectionViewDelegate, UIImagePickerControllerDelegate,
    UINavigationControllerDelegate {
    
      @IBOutlet weak var collectionView: UICollectionView!
    

    And instead of using

    FeedViewController().feedArray.append(feedItem)
    

    Now you can use:

    feedArray.append(feedItem)
    

    What the problem was, is that every time i used : “FeedViewController().fee…” I created a new instance, so i actually didn’t append the array properly.

    I hope it helped.