0

I am experiencing some weird behaviour and I am wondering if you can explain to me what is happening.

I have the following code

@implementation BAClient

NSString* _host = @"localhost:3000";

-(id)init{
    self = [super init];
    if(self){
//where the weird stuff happens
        NSString* str =[NSString stringWithFormat:@"%@/api", _host];
        _connection = [[BAConnectionManager alloc] initWithHost: str];
    }
    return self;
}
@end

after the first line of code runs (after the comment) - _host equals to localhost:3000. when the next line of code runs it equals to localhost:3000/api.

regardless of the code for the BAConnnectionManager constructor code - this is a behaviour I wouldn't expect - as I thought stringWithFormat creates a new string, and even if there is other magical way stringWithFormat works, no pointer to _host should be sent to the constructor.

any way BAConnectionManager Constructor:

@implementation BAConnectionManager

NSString* _host;

-(id) initWithHost:(NSString*)host{
    self = [super init];
    if(self){
        _host = host;
        _requestSuccessHandlers = [[NSMutableDictionary alloc] init];
        _requestFailureHandlers = [[NSMutableDictionary alloc] init];
    }
    return self;
}
@end

the two are on two different files so the fact that _host is in both of them shouldn't be a problem, or at least it would be a really weird behaviour, because they are defined on two completely different classes.

here is a prove that this is actually happening

I am under the impression that it really is something about ambiguity here, but I can't figure out why

gilmishal
  • 1,884
  • 1
  • 22
  • 37

1 Answers1

0

I have got it, since I am a newbie to Objective C I foolishly thought that you create private class members, just between the @implemintation and the @end - any way this fixed it:

@implementation BAClient{
    NSString* _host;
}

-(id)init{
    self = [super init];
    if(self){
//where the weird stuff happens
        _host =  = @"localhost:3000";
        NSString* str =[NSString stringWithFormat:@"%@/api", _host];
        _connection = [[BAConnectionManager alloc] initWithHost: str];
    }
    return self;
}
@end

and

@implementation BAConnectionManager{
     NSString* _host;
}
-(id) initWithHost:(NSString*)host{
    self = [super init];
    if(self){
        _host = host;
        _requestSuccessHandlers = [[NSMutableDictionary alloc] init];
        _requestFailureHandlers = [[NSMutableDictionary alloc] init];
    }
    return self;
}
@end
gilmishal
  • 1,884
  • 1
  • 22
  • 37