Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obj-, Instance variable used when 'self' is not set to the result of '[(super or self) init...]'

I asked a similar question to this already, but I still can't see the problem?

-(id)initWithKeyPadType: (int)value
{
    [self setKeyPadType:value];
    self = [self init];
    if( self != nil )
    {
        //self.intKeyPadType = value;

    }
    return self;
}

- (id)init {

    NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] 
                                                              autorelease];
    decimalSymbol = [formatter decimalSeparator];
....

The warning comes from the line above Instance variable used while 'self' is not set to the result of '[(super or self) init...]'

like image 246
Jules Avatar asked Nov 10 '11 22:11

Jules


People also ask

What does an instance variable represent?

An instance variable is a variable which is declared in a class but outside of constructors, methods, or blocks. Instance variables are created when an object is instantiated, and are accessible to all the constructors, methods, or blocks in the class. Access modifiers can be given to the instance variable.

What is an instance variable and how is it used in this level?

An Instance variable in Java is used by Objects to store their states. Variables that are defined without the STATIC keyword and are Outside any method declaration are Object-specific and are known as instance variables. They are called so because their values are instance-specific and are not shared among instances.

What is instance variable in oops?

What is instance variable in Java? Instance variables in Java are non-static variables which are defined in a class outside any method, constructor or a block. Each instantiated object of the class has a separate copy or instance of that variable. An instance variable belongs to a class.


1 Answers

What you are trying to do is technically OK, but at some stage you need to invoke [super init]. If your class's init method does a lot of common initialisation that other initWith... methods utilise, then put your [super init] in there. Also, always make sure that the class has been init'd before trying to play around with instance variables.

- (id) initWithKeyPadType: (int)value
{
    self = [self init]; // invoke common initialisation
    if( self != nil )
    {
        [self setKeyPadType:value];
    }
    return self;
}

- (id) init
{
    self = [super init]; // invoke NSObject initialisation (or whoever superclass is)
    if (!self) return nil;

    NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] 
                                                          autorelease];
    decimalSymbol = [formatter decimalSeparator];

    ...
like image 119
dreamlax Avatar answered Sep 27 '22 22:09

dreamlax