我有一个关于在objective-c 类中创建多个初始化器的简单问题。基本上我有一个类代表我的数据库(用户)中的一行。我目前有一个初始化程序,它根据用户 UserID(这也是数据库中的主键)初始化类,当传递 UserID 时,类将连接到 web 服务解析结果并返回一个初始化到相应行的对象在数据库中。
在这个数据库中有许多独特的字段(用户名和电子邮件地址),我还希望能够根据这些值初始化我的对象。但是我不确定如何拥有多个初始化器,我所阅读的所有内容都表明我可以自由地拥有多个初始化器,只要每个都调用指定的初始化器。如果有人可以帮助我解决这个问题,那就太好了。
我的初始化程序代码如下:
- (id) initWithUserID:(NSInteger) candidate {
self = [super init];
if(self) {
// Load User Data Here
NSString *soapMessage = [NSString stringWithFormat:
@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
"<soap:Body>\n"
"<GetByUserID xmlns=\"http://tempuri.org/\">\n"
"<UserID>%d</UserID>\n"
"</GetByUserID>\n"
"</soap:Body>\n"
"</soap:Envelope>\n", candidate
];
NSLog(@"%@",soapMessage);
// Build Our Request
NSURL *url = [NSURL URLWithString:@"http://photoswapper.mick-walker.co.uk/UsersService.asmx"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[theRequest addValue: @"http://tempuri.org/GetByUserID" forHTTPHeaderField:@"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSError *WSerror;
NSURLResponse *WSresponse;
webData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&WSresponse error:&WSerror];
xmlParser = [[NSXMLParser alloc] initWithData: webData];
[xmlParser setDelegate: self];
[xmlParser setShouldResolveExternalEntities: YES];
[xmlParser parse];
}
return self;
}
根据 Laurent 的评论,我尝试实施自己的解决方案,如果您能告知我此解决方案的任何明显问题,我将不胜感激:
我不完全确定我理解你的意思,我试图实现我自己的解决方案。如果您能告诉我您的想法,我将不胜感激:
- (id) init {
self = [super init];
if(self){
// For simplicity I am going to assume that the 3 possible
// initialation vectors are mutually exclusive.
// i.e if userName is used, then userID and emailAddress
// will always be nil
if(self.userName != nil){
// Initialise object based on username
}
if(self.emailAddress != nil){
// Initialise object based on emailAddress
}
if(self.userID != 0){ // UserID is an NSInteger Type
// Initialise object based on userID
}
}
return self;
}
- (id) initWithUserID:(NSInteger) candidate {
self.userID = candidate;
return [self init];
}
- (id) initWithEmailAddress:(NSString *) candidate {
self.emailAddress = candidate;
return [self init];
}
- (id) initWithUserName:(NSString *) candidate {
self.userName = candidate;
return [self init];
}
问候