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

iOS Build a Photo Browser iPhone App Gestures Creating a Detail View Controller

Tommy Choe
Tommy Choe
38,156 Points

@interface in implementation file

I get that the interface is used as a class extension in the implementation file to declare private instance variables, but why can't the variables be declared in the viewDidLoad method?

1 Answer

Michael Hulet
Michael Hulet
47,913 Points

In Objective-C, variables are only valid in the scope in which they are declared. Basically, if a variable is declared in the viewDidLoad method, they will only be available in the viewDidLoad method, and nowhere else. For example:

ViewController.h
@import UIKit;
@interface MyVC : UIViewController
// This is a public variable. It is accessible anywhere inside this class, as well as to any file that #imports this header
@property (strong, nonatomic) NSString *publicString;
@end
ViewController.m
#import "ViewController.h"

@interface MyVC ()
// This is a private variable. It is only accessible to methods inside this class
@property (strong, nonatomic) NSString *privateString;
@end

@implementation MyVC

-(void)viewDidLoad{
    NSString *localString = @"This is only accessible inside of viewDidLoad";
}

-(void)viewWillAppearAnimated:(BOOL)animated{
    // This is perfectly valid
    self.publicString = @"public";
    // This is also just fine
    self.privateString = @"private";
    // This is not
    localString = @"This code will not compile";
}
Tommy Choe
Tommy Choe
38,156 Points

Thank you for the awesome explanation!