Reputation: 1960
I am wondering if there is a more efficient way of identifying which phone numbers in a contact are populated than going through one by one and checking. Perhaps there are dictionary or array methods of which I am only dimly aware that would be good for working with varying collections of phone numbers for different contacts.
The contact object has strings for phone number and a lot of varieties, mobile, office, home, fax, main, toll free etc.
The dumb approach that I'm using is along the following lines:
NSString *office = myContact.officetel;
NSString *home = myContact.hometel;
NSString *mobile - myContact.mobiletel;
NSMutableArray *phonenums = [@[] mutableCopy];
if (office.length>=1) {
[phonenums addObject: office];
etc.
}
When I have assembled this array, I can then count its members to see if there is one or more and so forth. However, it is a tedious and inefficient approach it seems.
My goal is to be able to quickly identify if there is just one phone number and, if there are say, three out of five, offer up those possibilities to user.
Just wondering if there is a more powerful, efficient approach than the one above.
Upvotes: 0
Views: 106
Reputation: 6431
Easy as. This is how it can be done (pseudo-code).
NSArray numbers = @[
myContact.officetel,
myContact.hometel,
myContact.mobiletel
];
NSMutableArray *phonenums = [NSMutableArray new];
for(NSString *number in phonenums) {
if(number.length){
[phonenums addObject: number];
}
}
It can even be shorter, but less readable:
NSMutableArray *phonenums = [NSMutableArray new];
for(NSString *number in @[myContact.officetel, myContact.hometel, myContact.mobiletel]) {
if(number.length){
[phonenums addObject: number];
}
}
Update to the code above: pre-populating objects into an NSArray using array literals (syntactic sugar), i.e using @[a, b, c] can be unsafe if any of those elements are potentially nil. You will therefore in this case have to make sure that the getters for each of the number properties on the Contact class return empty string if the number is nil.
To address your request in the comments, you can add a function onto the Contact class called availableNumbers
and that would return a dictionary with key and number. The key would be the name of the number, e.g office, and the value would be the number itself:
Add this to your Contact.m
class (or whatever you called it)
-(NSDictionary*)availableNumbers
{
NSDictionary *keyedNumbers = [[NSMutableDictionary alloc] init];
if(self.officetel.length) {
[keyedNumbers setObject: self.officetel forKey: @"officetel"];
}
if(self.hometel.length) {
[keyedNumbers setObject: self.hometelforKey: @"hometel"];
}
if(self.mobiletel.length) {
[keyedNumbers setObject: self.mobiletelforKey: @"mobiletel"];
}
return keyedNumbers ;
}
Remember to add -(NSDictionary*)availableNumbers
to your .h file so that the method is public
Upvotes: 1