RCYup
RCYup

Reputation: 61

Allocating and Initializing in implementation .m file in Objective-C xcode

I'm trying to initialize an object under the implementation section of my program since I'm planning to use the same object for multiple methods. I'm getting an error by trying to do this and I was just wondering why. Here are some examples below:

@implementation Fraction {
    NSString *test = [[NSString alloc] init];
}

OR

@implementation Fraction {
    int x = 0;
}

Although if you don't initialize the variables, they work fine without any errors or warnings. I'm sure this is how the code was designed, but I was just curious as to why. Thanks in advance for your answers!

Upvotes: 3

Views: 2927

Answers (3)

eagle.dan.1349
eagle.dan.1349

Reputation: 631

In @implementation section you cannot initialize any of your variables, only declare them. For other things use - (id) init method, since it is logically called after allocation, like this: [[CustomObjectClass alloc] init]; In addition, to declare private variables, it is suggested to use class extensions in your .m file like this: @interface CustomClassName()

Upvotes: 0

rmaddy
rmaddy

Reputation: 318824

The curly brace section of @implementation is only for declaring instance variables. You can't initialize them or put any other code there.

The proper place to initialize the instance variables is in an init method:

@implementaiton Fraction {
    NSString *test;
    int x;
}

- (id)init {
    if ((self = [super init])) {
        test = @"";
        x = 0;
    }

    return self;
}

Upvotes: 8

CodaFi
CodaFi

Reputation: 43330

By surrounding @implementation in braces, you're declaring iVars, not declaring constants. And even if you weren't trying to declare a constant, you need to move your initialization into an -init flavored method if you wish the variable to hold an "initial value". If you were trying to declare a constant, it needs to be done outside of an @implementation block.

Upvotes: 2

Related Questions