iOS: can't figure out how to write the proper method - ios

I've managed NSUserDefaults and stuck with writing the method to filter the SQL select according to settings in standardUserDefaults.
My app shows 6 continents and user has an option to disable some of them. In my SQL methods I currently trying to manage it this way:
if (![[NSUserDefaults standardUserDefaults] boolForKey:#"europe"])
{
sqlContinents="SELECT cont.continentID,cont.continentName,cont.continentImage\
FROM Continents as cont\
WHERE cont.continentID <> 1";
}
It will work if user will disable only europe, but what if he will disable more continents... so I can't figure out how write code that will check which continents are disabled and omit them.
Of cause there's an option to write many "ifs" like
if(![[NSUserDefaults standardUserDefaults] boolForKey:#"europe"] && ....&&......), but I would be very thankful if someone will show me how to implement such method in more smart and elegant way. Thank you in advance.

You can create a WHERE string that holds all conditions before the SQL sentence.
NSString where = #"WHERE";
if (![[NSUserDefaults standardUserDefaults] boolForKey:#"europe"]){
where = [where stringByAppendingString: #" cont.continentID <> 1 "];
}
// Rest of continents...
sqlContinents = [#"SELECT cont.continentID,cont.continentName,cont.continentImage\
FROM Continents as cont " stringByAppendingString: where];

Another approach: sqlite knows the IN in where clauses, so could setup a string with continet IDs like "1, 4, 5" resulting in a statement
sql = [NSString stringWithFormat:#"... WHERE cont.continetID NOT IN (%#)", string];

Related

How should I localise with multiple parameters?

Let's say I have the following string:
[NSString stringWithFormat:#"Booked for %# at %#", colleagueName, time];
And I realise I've forgotten to localise that string, so I replace it:
[NSString stringWithFormat:NSLocalizedString(#"bookings.bookedFor", "Booked for user at time"), colleagueName, time];
Now when doing translations, I find that the language X needs the parameters the other way round; something closer to:
<time> for booking of <colleague> is done.
What is the best way to address the fact that now I need the second parameter of my formatted string to be time and the third to be colleagueName please?
As is often the case, my colleague found the solution almost as soon as I had asked on here! Apparently Objective-C has positional arguments
The positions are 1-indexed so %1$# refers to the first argument.
NSString *firstParam = #"1st";
NSString *secondParam = #"2nd";
NSLog(#"First %1$# Second: %2$#", firstParam, secondParam);
NSLog(#"Second %2$# First: %1$#", firstParam, secondParam);
This prints:
First 1st Second: 2nd
Second 2nd First: 1st
You can try like this:
NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];
if ([language isEqualToString:#"X"]) {//X is language code like "fr","de"
[NSString stringWithFormat:NSLocalizedString(#"bookings.bookedFor", "Booked for user at time"), time, colleagueName];
} else {
[NSString stringWithFormat:NSLocalizedString(#"bookings.bookedFor", "Booked for user at time"), colleagueName,time];
}

Unable to check the text value in my table in sqlite

I have one value which looks like this "00123-23" ,I have no idea about the datatype to be used to store in the table. So I used Text data type to store this value.But When I try to check this value, the query is saying that there is no such value in my table, but actually there is a value. Here is my query:
NSString *x_accountNo;
x_accountNo=[_substrings objectAtIndex:2]; //x_accountNo=00123-23
NSString *query_newAccount = [NSString stringWithFormat:#"SELECT * FROM MYTABLE WHERE ACCOUNT=%# ",x_accountNo];
BOOL recordExist_newAccount = [self recordExistOrNot_newAccount:query_newAccount];
if (!recordExist_newAccount) {
nslog(#"no data");
}
Everytime I execute this statement, It is giving me no data . Could you please tell me what I am doing wrong here?
You might need to have string inside quotes:
SELECT * FROM MYTABLE WHERE ACCOUNT='%#'

if statements and stringWithFormat

I need to know if there is a way to use if statements to display certain nsstrings, depending on whether or not that NSString contains any data.
I have an nsstringcalled visitorInfo.
The string uses data from other strings (i.e. which operating system the user is running) and displays that info. Here is an example of what I'm talking about:
NSString *visitorInfo = [NSString stringWithFormat:#"INFO\n\nVisitor Location\n%#\n\nVisitor Blood Type\n\%#", _visitor.location, _visitor.bloodType];
And it would display like this:
INFO
Location
Miami, FL
Blood Type
O positive
However, I have several pieces of data that only load if the user chooses to do so. i.e their email address.
This section of code below would do what I want, but my visitorInfo string contains tons of different strings, and if I use this code below, then it won't load any of them if the user chooses not to submit his blood type.
if ([self.visitor.bloodType length] > 0) {
NSString *visitorInfo = [NSString stringWithFormat:#"INFO\n\nVisitor Location\n%#\n\nVisitor Blood Type\n\%#", _visitor.location, _visitor.bloodType];
}
So basically if their is data stored in bloodType then i went that code to run, but if there isn't any data I only want it to skip over bloodType, and finish displaying the rest of the data.
Let me know if you have any more questions
Additional details. I'm using an NSString for a specific reason, which is why I'm not using a dictionary.
Just build up the string as needed using NSMutableString:
NSMutableString *visitorInfo = [NSMutableString stringWithFormat:#"INFO\n\nVisitor Location\n%#, _visitor.location];
if ([self.visitor.bloodType length] > 0) {
[visitorInfo appendFormat:#"\n\nVisitor Blood Type\n\%#", _visitor.bloodType];
}
You can check if a string has any data in it by using the following
if([_visitor.location length]<1){
//This means there's no data and is a better way of checking, rather than isEqualToString:#"".
}else{
//there is some date here
}
** EDIT - (just re-reading your question, sorry this answer is dependant on _visitor.location being a string in the first place)*
I hope this helps
Try this -
NSString *str = #"INFO";
if (_visitor.location) {
str = [NSString stringWithFormat:#"\n\nVisitor Location\n%#",_visitor.location];
}
if (_visitor.bloodType) {
str = [NSString stringWithFormat:#"\n\nVisitor Blood Type\n\%#",_visitor.bloodType];
}

How to Search a List of Names in iOS?

So basically I want to use a UISearchBar to search an Array of Names.
Inside the Array the Names have this Format:
[FIRST NAME] ([SECOND NAME]) [LAST NAME]
Using
if (![string rangeOfString:seachTextPart].location == NSNotFound)
I have managed to search Names entering ONLY the FIRST NAME into the UISearchBar.
But as soon as I enter a SPACE i get NO RESULTS.
Also I want to be able to search by entering just the LAST NAME.
Can anyone please help me?
Thanks
Assuming your format is follow:name = #"[John]([James])[Smith]";
Searching [name rangeOfString:#"John"] would yield found.
Searching [name rangeOfString:#"John "] would yield not found, since #"John " is not in name
But in this case, [name rangeOfString:#"Smith"] would yield found.
Try this: Remove all spaces and lower case strings
searchTerm = [[searchTerm stringByReplacingOccurrencesOfString:#" " withString:#""] lowercaseString];
NSRange searchName = [[name lowercaseString] rangeOfString:searchTerm];
If you want to test, just simply do this"
if (searchName == 0) //it does not match
Byte's code works unless they type "John Smith." If you want something more robust you can use - (NSArray *)componentsSeparatedByString:(NSString *)separator and then search for any of the strings in the Array. So Typing "John Smith" would return all of the Johns and all of the Smiths
here:
NSArray *theTerms = [searchTerm componentsSeparatedByString:#" "];
then run a for loop through all of theTerms and check them against your names adding the ones that contain the search terms to an array and then displaying them.

How do I use NSRange with this NSString?

I have the following NSString:
productID = #"com.sortitapps.themes.pink.book";
At the end, "book" can be anything.... "music", "movies", "games", etc.
I need to find the third period after the word pink so I can replace that last "book" word with something else. How do I do this with NSRange? Basically I need this:
partialID = #"com.sortitapps.themes.pink.";
You can try a backward search for the dot and use the result to get the desired range:
NSString *str = #"com.sortitapps.themes.pink.book";
NSUInteger dot = [str rangeOfString:#"." options:NSBackwardsSearch].location;
NSString *newStr =
[str stringByReplacingCharactersInRange:NSMakeRange(dot+1, [str length]-dot-1)
withString:#"something_else"];
You can use -[NSString componentsSeparatedByString:#"."] to split into components, create a new array with your desired values, then use [NSArray componentsJoinedByString:#"."] to join your modified array into a string again.
Well, although this isn't a generic solution for finding characters, in your particular case you can "cheat" and save code by doing this:
[productID stringByDeletingPathExtension];
Essentially, I'm treating the name as a filename and removing the last (and only the last) extension using the NSString method for this purpose.

Resources