Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,843 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:

@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;
#import "ViewController.h"

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

@implementation MyVC

    NSString *localString = @"This is only accessible inside of viewDidLoad";

    // 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!