David Lopes
David Lopes

Reputation: 33

Declaring instance variables in iOS - Objective-C

Ok, I've read a lot around these days about this topic and I alwyas get confused because the answers is different every search I make.

I need to know the best way to declare instance variables in iOS. So far I know I should only declare them inside .m file and leave .h clean. But I can't do it: the compiler gives me compilation erros.

Here is some code from .m only.

@interface UIDesign ()

// .m file
{
    NSString *test2 = @"test2";
}

@property (nonatomic, assign) int privateInt;

@end

@implementation UIDesign
{
    NSString *test1 = @"test1";
}

Both strings are declared incorrectly and I don't know why. The compiler says: expected ';' at end of declaration list.

So the question is: how can I declare instance variables? I will only need them inside the class.

Upvotes: 1

Views: 18541

Answers (2)

FluffulousChimp
FluffulousChimp

Reputation: 9185

You are attempting to add an instance variable to a class extension or category which is unsupported. [EDIT 2013-05-12 06-11-08: ivars in class extension are supported, but not in categories.] As an alternative:

@interface UIDesign : NSObject
@end

@interface UIDesign ()

@property (nonatomic, assign) int privateInt;
@end

@implementation UIDesign

@synthesize privateInt = _privateInt;

- (void)someMethod {
    self.privateInt = 42;
}

@end

On the other hand, if you just want to declare an instance variable inside the implementation, just do it there:

@implementation UIDesign {
    int _privateInt;
}

@end

EDIT: just noticed that you're also attempting to initialize instance variables in the declaration which is also unsupported. So:

@interface UIDesign : NSObject
@end

@implementation UIDesign {
    NSString *_test;
}

- (id)init {
    self = [super init];
    if( !self ) return nil;

    _test = @"Foo";

    return self;
}

@end

Upvotes: 1

Gabriel
Gabriel

Reputation: 3359

You cannot initialize instance variables. They are all initialized to nil or zeroes. So compiler expect a semicolon when you are writing an equal sign.

You can initialize them in init method.

Upvotes: 1

Related Questions