Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 298
RCYup Avatar asked Mar 07 '26 17:03

RCYup


2 Answers

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;
}
like image 187
rmaddy Avatar answered Mar 09 '26 05:03

rmaddy


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.

like image 28
CodaFi Avatar answered Mar 09 '26 07:03

CodaFi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!