简体   繁体   中英

NSString stringWithFormat affects parameter

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.

这证明这实际上正在发生

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

I have got it, since I am a newbie to Objective CI 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM