Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jared Watkins
10,756 PointsHow do I access methods in ViewController.swift from within my AppDelegate.swift?
I thought methods I had created in the view controller and other swift files would be available to me in AppDelegate, but they are not.
2 Answers
David Fry
13,267 PointsHello Jared! You have to get an instance to your ViewController in the AppDelegate.
Class ViewController:
{
// Using a property
var firstName: String!
func printSomething(name: String)
{
println("Hello \(name).... All your base belong to us!")
}
}
Class AppDelegate: UIResponder, UIApplicationDelegate
{
// View controller instance, this is the hook to your ViewController
var vc = ViewController()
func application(application: UIApplication, didFinishLaunchingWithOptions: [NSObject: AnyObject]?) -> Bool
{
vc.firstName = "Jared"
// This is calling the function from the view controller
vc.printSomthing(vc.firstName)
return true
}
}
I hope that helps. Normally, you try not to put too much in your AppDelegate.
David
Tony Warner
1,631 PointsHi, This doesn't seem to work if the view controller method is reloading a table / collectionView... The error is Unexpectedly Found Nil While Unwrapping. Does anyone know why that might be? Also, what way would you be able to refresh a viewController's table / collectionView from an appDelegate method?
Chris Bailey
2,237 PointsTony, did you manage to find an answer? I'm running into the same road block
Jared Watkins
10,756 PointsJared Watkins
10,756 PointsWorks like a charm. Thanks David!