快速附加到来自不同类的数组 [英] append to array from different class in swift

查看:21
本文介绍了快速附加到来自不同类的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试附加到我的数组

Im trying to append to my array

var feedArray: [AnyObject] = []

来自另一个班级.我有 2 个班级:

from another class. I have 2 classes:

class FeedViewController: UIViewController, UICollectionViewDataSource,
     UICollectionViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

      var feedArray: [AnyObject] = []

class AddEditViewController: UIViewController, NSFetchedResultsControllerDelegate,
      UIImagePickerControllerDelegate, UINavigationControllerDelegate {

我想在我的AddEditViewController"中附加数组feedArray".但我没办法.我试过了:

I want to in my "AddEditViewController" append the array "feedArray". But I'm not able. I have tried:

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

我什至试着把

print(FeedViewController().feedArray.count)

但即使数组有 3 个对象,结果始终为 0.

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?

推荐答案

所以,在玩了一会儿并尝试学习后,我找到了解决方案

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] = []

更改它以便您拥有:

import UIKit
import CoreData
import MobileCoreServices

 var feedArray: [AnyObject] = []

class FeedViewController: UIViewController, UICollectionViewDataSource,
UICollectionViewDelegate, UIImagePickerControllerDelegate,
UINavigationControllerDelegate {

  @IBOutlet weak var collectionView: UICollectionView!

而不是使用

FeedViewController().feedArray.append(feedItem)

现在您可以使用:

feedArray.append(feedItem)

问题是,每次我使用:FeedViewController().fee..."我创建了一个新实例,所以我实际上没有正确附加数组.

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.

希望对您有所帮助.

这篇关于快速附加到来自不同类的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆