I have a rather simple question and forgive me if it is sacrilege to ask it haha.
I have 6 variables that I need to test if they are null or if their length is 0. So I figured that maybe I could use two switches, one for testing if it is string == [NSNull null] and one for testing string.length == 0. Instead of making a huge and complicated if. A switch such as:
switch([NSNull null])
{
case string:
Do something
break;
case string2:
Do something else
break;
// etc...
}
and then another one such as:
switch( length==0) //I know length==0 doesn't work, but maybe you know an alternative
{
case string:
Do something
break;
case string2:
Do something else
break;
// etc...
}
Thank开发者_如何学Go you for your help!
For your first switch statement, you can't an object within your switch brackets (an instance of NSNull is returned [NSNull null]
). You must use primitives within the bracket only. Furthermore, your throught process is clearly flawed, as [NSNull null] will always return the same sort of object (an object that represents a null value), and therefore you have nothing to switch on, as opposed to switching on an integer, whereby your case statements could be for different integers.
For your second switch statement, you cannot (again) use objects for your cases (NSString is, of course, an object). The best thing to do here would be to use a series of if else clauses as follows:
if ([string length] == 0)
{
if ([string isEqualTo:@"firstStringToCheck"])
{
// Do something.
}
else if ([string isEqualTo:@"secondStringToCheck"])
{
// Do something else.
}
}
Notice that I also use the instance method named length in order to get the length of the string and check that it is 0. This seems to be what you were trying to do in your example, but also makes absolutely no sense to me. Why would you want to check strings with other strings when you know that if the string's length is 0 it couldn't possibly match any strings!
You're totally misunderstanding how the switch statement works. It's designed to test multiple possible variables for a set of possible values. Specifically to replace code like:
if (value == 0)
NSLog (@"zero");
else if (value == 1)
NSLog (@"one");
else if (value == 2)
NSLog (@"two");
else if (value == 3)
NSLog (@"three");
else if (value == 4)
NSLog (@"four");
else if (value == 5)
NSLog (@"five");
else
NSLog (@"Integer out of range");
with
switch (value)
{
case 0:
NSLog (@"zero");
break;
case 1:
NSLog (@"one");
break;
case 2:
NSLog (@"two");
break;
case 3:
NSLog (@"three");
break;
case 4:
NSLog (@"four");
break;
case 5:
NSLog (@"five");
default:
NSLog (@"Integer out of range");
break;
}
what you're currently doing will give you unexpected results. Use an if statement, or write a function to handle testing for null. See enter link description here, where I shamelessly cribbed these examples from for more information.
精彩评论