objective c - Singleton pattern with parameter -
in iphone application, i'm using subclass of afhttpclient access rest web service. want requests handled 1 instance of api client use singleton pattern.
this works fine when service running on once url. can use constant value set url.
now, in final version of application, each app talk service installed in corporate network.
so getting service url remote configuration. singleton pattern still choice here? how supposed parameterise if url change during runtime of app ?
cheers
#import "fooapiclient.h" #import "afjsonrequestoperation.h" static nsstring * const kfooapibaseurlstring = @"http://192.168.0.1"; @implementation fooapiclient + (instancetype)sharedclient { static fooapiclient *_sharedclient = nil; static dispatch_once_t oncetoken; dispatch_once(&oncetoken, ^{ _sharedclient = [[self alloc] initwithbaseurl:[nsurl urlwithstring:kfooapibaseurlstring]]; }); return _sharedclient; } - (id)initwithbaseurl:(nsurl *)url { self = [super initwithbaseurl:url]; if (!self) { return nil; } [self registerhttpoperationclass:[afjsonrequestoperation class]]; [self setdefaultheader:@"accept" value:@"application/json"]; return self; } @end
this solution. instead of subclassing afhttpclient, set property , re-instantiate if url changes:
#import "fooapiclient.h" #import "afjsonrequestoperation.h" #import "afhttpclient.h" static nsstring * const kfooapibaseurlstring = @"http://192.168.0.1"; @interface fooapiclient () @property afhttpclient * httpclient; @end @implementation fooapiclient + (instancetype)sharedclient { static fooapiclient *_sharedclient = nil; static dispatch_once_t oncetoken; dispatch_once(&oncetoken, ^{ _sharedclient = [[self alloc] initwithbaseurl:[nsurl urlwithstring:kfooapibaseurlstring]]; }); return _sharedclient; } - (id)initwithbaseurl:(nsurl *)url { self = [super init]; if (!self) { self.httpclient = [self setupclientforurl:url]; } return self; } -(afhttpclient*) setupclientforurl:(nsurl*) url { afhttpclient * httpclient = [[afhttpclient alloc] initwithbaseurl:url]; [httpclient registerhttpoperationclass:[afjsonrequestoperation class]]; [httpclient setdefaultheader:@"accept" value:@"application/json"]; return httpclient; } #pragma mark - remoteconfigurationdelegate -(void) apiurlchanged:(nsurl*) newurl { self.httpclient = [self setupclientforurl:newurl]; } #pragma mark - public -(void) consumeapi:(completionblock) completion { [self.httpclient getpath:@"foo" parameters:nil success:^(afhttprequestoperation *operation, id responseobject) { if(completion) { completion(responseobject, nil); } } failure:^(afhttprequestoperation *operation, nserror *error) { if(completion) { completion(nil, error); } }]; } @end
Comments
Post a Comment