Why Does String Not Equal What Is Stored? - iphone

This is a simple, odd question...
if(tableViewNum == #"One") {
if ([drinkArray objectAtIndex:0] == currentDate) {
[updatedArray addObject:drinkArray];
NSLog(#"MADE THE ELSE1");
}
NSLog(#"MADE THE ELSE2");
}
else if (tableViewNum == #"Two") {
if ([[drinkArray objectAtIndex:0] isEqualToString:yesterdayDate])
[updatedArray addObject:drinkArray];
} else {
NSLog(#"MADE THE ELSE %#",tableViewNum);
[updatedArray addObject:drinkArray];
}
In the very first if statement I ask if tableViewNum == #"One"
But I don't go in that section of the if statement even though tableViewNum actually does equal #"One"
As you can see the very last NSLog all ways comes out as
MADE THE ELSE One
But if tableViewNum really equaled One it would have gone through the if statement not the else statement code...?????

You can't compare strings with the == operator. Use isEqualToString instead:
if([tableViewNum isEqualToString:#"One"]) {
// etc.
… and the same for the rest of the conditions. You're already doing it right in the second block.

To be more specific, you shouldn't compare ANY objects using ==. This compares just the pointers. Use [obj isEqual: otherObj] or with NSStrings isEqualToString: as described above.

Related

How to Compare Two NSStrings which contain float values? [duplicate]

This question already has answers here:
Compare version numbers in Objective-C
(15 answers)
Closed 9 years ago.
I have two strings, one contains the value "5.2.3" and another one contain a value like "5.2.32". My question is: how to compare these two strings?
if ([string1 integerValue] >= [sting2 integerValue])
{
NSLog(#"process");
}
I tried above line but not got it.
Well correct answer has been already given. Because I have spent my half an hour on it so I don't want to waste it.
-(BOOL)string:(NSString*)str1 isGreaterThanString:(NSString*)str2
{
NSArray *a1 = [str1 componentsSeparatedByString:#"."];
NSArray *a2 = [str2 componentsSeparatedByString:#"."];
NSInteger totalCount = ([a1 count] < [a2 count]) ? [a1 count] : [a2 count];
NSInteger checkCount = 0;
while (checkCount < totalCount)
{
if([a1[checkCount] integerValue] < [a2[checkCount] integerValue])
{
return NO;
}
else if([a1[checkCount] integerValue] > [a2[checkCount] integerValue])
{
return YES;
}
else
{
checkCount++;
}
}
return NO;
}
And you can call this method like this:-
if([self string:str1 isGreaterThanString:str2])
{
NSLog(#"str2 is lower than the str1");
}
else
{
NSLog(#"str1 is lower than the str2");
}
It would appear that what you have here are not really "float" values, but some kind of multi-part "number" (akin to software version numbering?) that is not going to be covered by any of the standard conversions, but will also not compare "correctly" as just simple strings.
First you need to specify exactly what your comparison rules are. For example, I suspect you want something like:
1.2 > 1.1
1.1.1 > 1.1
1.11 > 1.2
1.2.3 > 1.2.2
1.2.22 > 1.2.3
(in other words, split the string up by "."s, and do a numeric comparison on each component). You'll have to decide how you want to handle things like letters, other delimiters, etc. showing up in the input. For example is 1.0b1 > 1.01 ?
Once you settle on the rules, write a method (returning NSComparisonResult) to implement the comparison. If you want to get fancy, you can even define your comparison method in a category on NSString, so you could do things like
if ([string1 mySuperDuperCompareTo:string2] == NSOrderedAscending) {
NSLog(#"%# < %#", string1, string2);
} // ... etc ...
see also How to let the sortedArrayUsingSelector using integer to sort instead of String?
#The Tiger is correct. Sorry to misunderstood your question. I have already mark deleted as my older answer. Here is the updated one.
As there are multiple . (dots) available here is the new solution. This will check value first like 5.2.3 and 5.2.32 are there. Then,
check first value 5 - same
so check next 2 - same
check next 3 and 32 - 32 is larger
also check for the same string as well (Also one of the probability)
Here is the logic - I have not compiled but this is base idea - there might require some correction
// separate from "."
NSArray *arrString1 = [string1 componentSeparatedBy:#"."];
NSArray *arrString2 = [string1 componentSeparatedBy:#"."];
BOOL isString1Bigger = NO; // a variable to check
BOOL isString2Bigger = NO; // a variable to check
// check count to run loop accordingly
if ([arrString1 count] <= [arrString2 count]) {
for (int strVal=0; strVal<[arrString1 count]; strVal++) {
// compare strings value converted into integer format
// when you get larger then break the loop
if([[arrString1 objectAtIndex:strVal] intValue] > [[arrString2 objectAtIndex:strVal] intValue]) {
isString1Bigger = YES;
break;
}
}
if ([arrString1 count] > [arrString2 count]) {
// use arrString2 in loop and isString2Bigger as a mark
}
// if after running both the if condition still require to check if both are same or not, for that,
if ((isString1Bigger == NO) && (isString2Bigger == NO)) {
// same string values
}
There might some modification required to run over. But its the base concept to compare string value provided by you.

Sort class instance alphabetically

I have this code which works on numbers (distance) which allows me to sort by closest to farthest. However I would like to do something similar but instead sort alphabetically. So I need to sort self.names alphabetically essentially. Also, I'd like to eventually sort self.names alphabetically and if you have identical names then sort those by distance. Is this possible?
- (NSComparisonResult)sortByDistFromVor:(radiostations *)anObject
{
if ([self.distFromVor doubleValue] < [anObject.distFromVor doubleValue]) {
return NSOrderedAscending;
} else if ([self.distFromVor doubleValue] > [anObject.distFromVor doubleValue]) {
return NSOrderedDescending;
}
return NSOrderedSame;
}
String implements a comparison, so the radiostations class (whose name ought to be capitalized by convention) can implement it's name comparison like this:
- (NSComparisonResult)sortByName:(radiostations *)anObject {
return [self.name compare:anObject.name];
}
And to get a secondary sort as you described:
- (NSComparisonResult)sortByNameThenDistance:(radiostations *)anObject {
NSComparisonResult result = [self sortByName:anObject];
return (result == NSOrderedSame)? [self sortByDistFromVor:anObject] : result;
}

How to compare self.title to a string in Objective C?

What am I doing wrong in the below code? My if statement is missing something:
if ([self.title] = "Upcoming Events") {
} else {
}
Correct would be:
if( [self.title isEqualToString:#"Upcoming Events"] )
self.title is a pointer, you can only compare it to other pointers using == not their values.
if ([self.title isEqualToString:#"Upcoming Events"]) {
NSLog(#"True");
} else {
NSLog(#"False");
}
You just have to write like this:
if([self.title isEqualToString:#"Upcoming Events"])
{
}
else
{
}
also .... in a if you should use "==" instead of "=". When there is "==" it is checking if they are equal while if there is "=" it gives the first one the value of the second.

How to check if array is null or empty?

I want to check if my array is empty or null, and on base of which I want to create a condition for example.
if(array == EMPTY){
//do something
}
I hope I'm clear what I am asking, just need to check if my array is empty?
regards
if (!array || !array.count){
...
}
That checks if array is not nil, and if not - check if it is not empty.
if ([array count] == 0)
If the array is nil, it will be 0 as well, as nil maps to 0; therefore checking whether the array exists is unnecessary.
Also, you shouldn't use array.count as some suggested. It may -work-, but it's not a property, and will drive anyone who reads your code nuts if they know the difference between a property and a method.
UPDATE: Yes, I'm aware that years later, count is now officially a property.
you can try like this
if ([array count] == 0)
Just to be really verbose :)
if (array == nil || array.count == 0)
Best performance.
if (array.firstObject == nil)
{
// The array is empty
}
The way to go with big arrays.
if (array == (id)[NSNull null] || [array count] == 0) {
NSLog(#"array is empty");
}
Swift 3
As in latest version of swift 3 the ability to compare optionals with > and < is not avaliable
It is still possible to compare optionals with ==, so the best way to check if an optional array contains values is:
if array?.isEmpty == false {
print("There are objects!")
}
as per array count
if array?.count ?? 0 > 0 {
print("There are objects!")
}
There are other ways also and can be checked here
link to the answer
As nil maps to 0, which equals NO, the most elegant way should be
if (![array count])
the '==' operator is not necessary.
You can also do this kind of test using
if (nrow>0).
If your data object is not formally an array, it may work better.
null and empty are not the same things , i suggest you treat them in differently
if (array == [NSNull null]) {
NSLog(#"It's null");
} else if (array == nil || [array count] == 0) {
NSLog(#"It's empty");
}
if (array == nil || array.count == 0 || [array isEqaul [NSNull Null]])
In Swift 4
if (array.isEmpty) {
print("Array is empty")
}
else{
print("Array is not empty")
}

How to know whether a UITextField contains a specific character

How would I say that if a UITextField has #"-" in it, do something.
Right now my code is like this. It doesn't seem to work:
if (MyUITextField.text == #"-") {
NSRange range = {0,1};
[a deleteCharactersInRange:range];
MyUITextField.text = MyUILabel.text;
}
I know that I am doing something very wrong with the code. Please help.
try changing == to [MyUITextField.text isEqualToString:#"-"]
as == tests to see if they are the same object, while isEqualToString compares the contents of the strings.
Assuming your string is defined as:
NSString *str = #"foo-bar";
To check if your string contains "-" you can do the following:
if ([str rangeOfString:#"-"].length > 0)
{
NSLog(#"Contains -");
}
It looks like you wanted to delete the first character if a string starts with a given character. In this case you can do something like this:
if ([str hasPrefix:#"f"])
{
NSLog(#"Starts with f");
}