简体   繁体   中英

How do I access an iVar from a different .swift file within the same target?

I want to access an IBOutlet declared in my ViewController.swift from
my ImageDownloader.swift file; ie, (ImageDownloader.swift --> ViewController.swift).
But the compiler can't find it.

在此处输入图片说明

Note: the target object is a member of a class (ViewController) and hence, isn't global.

ViewController.swift: {Calling Target}

在此处输入图片说明

ImageDownloader.swift: {Calling Source}

let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in
    if let httpRes = response as? NSHTTPURLResponse {
       if httpRes.statusCode == 200 {
           self.image = UIImage(data:data)

           dispatch_async(dispatch_get_main_queue(), {
                viewcontroller.collectionView.reloadData()  // ...compiler error.
           })

        }
    }
}

Compiler Error:

...Use of unresolved identifier 'collectionView'

在此处输入图片说明 How do I reference an IBOutlet var in a different .swift file?


Here's the Obj-C version of what I'm trying to do:

 @property (weak, nonatomic) IBOutlet UICollectionView *collectionView; ... dispatch_async(dispatch_get_main_queue(), ^{ [self.collectionView reloadData]; }); 

...where rather than referencing collectionView from within the SAME swift file, I reference form another swift file.

...perhaps this is a poor paradigm to follow; to use closures instead, per feedback.

The problem is your local viewcontroller variable. I assume this is actually a property (referring to it as self.viewcontroller would help reduce confusion). I suspect you have a typo there. Maybe you meant self.viewController for instance.

That said, you should not try to access another view controller's IBOutlets directly. IBOutlets are implementation details of a view controller. They are subject to change any time you modify your UI.

Ideally, the view controller should be a delegate of whatever object this is, or should have passed a closure to this object, so that the view controller is able to manage reloading its own collection view.

As a second best approach, your view controller should have a method, such as refresh() that you can call to do whatever UI is required when the data has changed. That way this object does not need internal details about the view controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM