Can I make a switch([NSNull null])? (Objc) - iphone

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 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.

Related

Dart switch statement - Case expressions must be constant

I looked at a few questions regarding this for other languages and some suggest using final but that doesn't seem to work with Dart.
I'm passing in arguments so surely the switch statement cannot contain constants only? A switch statement, much like an if statement is asking if it is or not..ie it's unknown so I don't see how a switch statement can be useful if they have to be constants...?
setCategory(arga, argb) {
int result;
switch (true) {
case (arga >= 0 && arga < 3 && argb < 35):
result = 16;
break;
case (arga >= 0 && arga < 3 && argb >= 35):
result = 15;
break;
etc
It's returning the error Case expressions must be constant regarding the values arga and argb in the case expressions. What's the best way to remedy this or do I have to use an if statement?
The switch case expressions must be constants for sure.
You have to use if/then chains to do multiple tests based on non-constant values.
You cannot use arguments from the surrounding function in a switch case. What you are trying to do here is not supported by the Dart switch statement.
The Dart switch statement is deliberately kept very simple, so that a compiler can know all the possible cases at compile-time. That's why they must be compile-time constants.
Switch statements are still useful for some kinds of switching, like on enums:
enum Nonse { foo, bar, baz; }
String fooText(Nonse non) {
switch (non) {
case Nonse.foo: return "foo";
case Nonse.bar: return "bar";
case Nonse.baz: return "baz";
}
throw ArgumentError.notNull("non");
}
You can also switch over constant string values or integer values.
There are some rules for Switch Case
The default case is optional.
All case expression must be unique.
The case statements can include only constants. It cannot be a variable or an expression.
The data type of the variable and the case expression must match.
There can be any number of case statements within a switch.
you should use 'If Else' statement
Switch statement requires a constant -> it means already initialized variable with final value
switch (expression) {
case ONE : {
statement(s);
}
break;
case TWO: {
statement(s);
}
break;
default : {
statement(s);
}
}
for(int x=0; x<1; x++){
if(ing5<8 && toWhatDegreeRand<=10 && toWhatDegreeRand>7){
toWhatDegreeRand=9;
}
if(ing4<8 && toWhatDegreeRand<=7 && toWhatDegreeRand>5){
toWhatDegreeRand=6;
}
if(ing3<8 && toWhatDegreeRand<=5 && toWhatDegreeRand>3){
toWhatDegreeRand=4;
}//....
}
It can be a little useful.

if else statements confusion Objective-C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In Xcode, I have an if and an else statement.
I would like to make the statement have multiple conditions, but only one of them have to be 'YES'.
For example:
I have a NSString, the value of that string is:
[NSstring stringWithFormat:#"ABCDEFG12345"];
I need to have my if statement check for if A or 1 or 5 is in the string. I understand how to use [string rangeOfString:#"CheckHere"];.
I need my if statement to find one or all of those given letters/numbers. If one is found, execute the given code, if two are found, execute the given code, if all three are found, execute the given code.
You need no if-else. You can do something like this.
NSString* string = #"ABCDEFG12345";
int foundA = [string rangeOfString:#"A"].location == NSNotFound ? 0 : 1;
int found1 = [string rangeOfString:#"1"].location == NSNotFound ? 0 : 1;
int found5 = [string rangeOfString:#"5"].location == NSNotFound ? 0 : 1;
int foundCount = foundA + found1 + found5;
switch(foundCount) {
case 1: [self executeOne]; break;
case 2: [self executeTwo]; break;
case 3: [self executeThree]; break;
}
One possible approach:
Let's assume you can piece together the (actually somewhat tedious) use of rangeOfString and rangeOfCharacter calls together and can write a method like this:
-(NSInteger)numberOfMatchesFoundInString:(NSString*)inputString;
which lets you pass in a string, and returns a 0,1,2... based on how many matches are found.
To use this convenient result in a highly readable way, you can use a switch statement.
NSInteger* matches = [self numberOfMatchesFoundInString:someString];
switch (matches) {
case 0:
//execute some code here for when no matches are found
break;
case 1:
//execute some different code when one match is found
break;
case 2:
//you get the idea
break;
default:
//some code to handle exceptions if the numberOfMatchesFoundInString method went horribly wrong
break;
Of course some people will tell you that this is functionally no different than calling
if (someCondition) {
//do some stuff
}
else if (someOtherCondition) {
//do some different stuff
}
etc...
but really, you can make either one work.
There are a few useful techniques you can use for string comparisons.
If you just need test if your string is one of a list of strings, use something like this:
NSArray *options = #[#"first", #"second", #"third"];
if ([options contains:inputString]) {
// TODO: Write true block
} else {
// TODO: Write else block
}
If you want to check if your string contains at least one character from a set, use NSString -rangeOfCharacterFromSet:.
Unfortunately, if you want to check if your string contains one or more strings, you have no choice but to write it out the long way. If you do it frequently enough, you may choose to write a class category.
- (BOOL)containsAtLeastOneSubstring:(NSArray *)substrings
{
for (NSString *aString in substrings) {
NSRange range = [self rangeOfString:aString];
if (range.location!=NSNotFound) {
return YES;
}
}
return NO;
}
-

How to check null value of object in decision statement for Objective C

I am getting a object value from server as null value when NSlog this object.I want to identify it in if-else decision statement. How can I check it because nil have reference to a unknown object which not means NULL.and i can't compare it with zero too.
How can i identify that this value is NULL, i have a crash on this point.I have tried #try - #catch block too but all gone in vain.
Any suggestion for this problem.
As others have pointed out, there are many kinds of "null" under Cocoa/Objective C.
But one further thing to note is that [object isKindOfClass:[NSNull class]] is pointlessly complex since [NSNull null] is documented to be a singleton so you can just check for pointer equality. See Topics for Cocoa: Using Null
So use this :-
if (title == (id)[NSNull null] || title.length == 0 ) title = #"Something";
Note how you can use the fact that even if title is nil, title.length will return 0/nil/false, ie 0 in this case, so you do not have to special case it. This is something that people who are new to Objective C have trouble getting used to, especially coming form other languages where messages/method calls to nil crash.
If you want in detail what is the difference between nil, Nil and null, you can check this article What is the difference between nil, Nil and null.
You can try following code to check for NULL values from server:
if (nil == str || NSNull.null == (id)str) {
//Object has Null value
}
else{
// Object has some value
}
str is string value which contain server value.
This may helps you.
The Best Approach is :
if([yourObject isKindOfClass:[NSNull null]])
{
// yourObject is null.
}
else
{
// yourObject is not null.
}

Why can't I use an NSInteger in a switch statement?

Why doesn't this work:
NSInteger sectionLocation = 0;
NSInteger sectionTitles = 1;
NSInteger sectionNotifications = 2;
switch (section) {
case sectionLocation:
//
break;
case sectionTitles:
//
break;
case sectionNotifications:
//
break;
default:
//
}
I get this compile error:
error: case label does not reduce to an integer constant
Is it not possible to use NSInteger's like this? If so, is there another way to use variables as cases in a switch statement? sectionLocation etc. have variable values.
The problem isn't the scalar type, but that the case labels may change value when they are variables like that.
For all intents and purposes, the compiler compiles a switch statement as a set of gotos. The labels can't be variable.
Use an enumerated type or #defines.
The reason is that the compiler will often want to create a 'jump table' using the switch value as the key into that table and it can only do that if it's switching on a simple integer value. This should work instead:
#define sectionLocation 0
#define sectionTitles 1
#define sectionNotifications 2
int intSection = section;
switch (intSection) {
case sectionLocation:
//
break;
case sectionTitles:
//
break;
case sectionNotifications:
//
break;
default:
//
}
The problem here is you are using variables. You can only use constants in switch statements.
Do something like
#define SOME_VALUE 1
or
enum Values {
valuea = 1,
valueb = 2,
...
}
And you will be able to use valuea and so forth in your switch statement.
If your case values truly change at runtime, that's what the if...else if...else if construct is there for.
or just do this
switch((int)secion)

Compile Error with: switch, "expected expression before"

Cut to the chase I have recreated my problem as it is fairly self explanatory.
this complies without error:
switch (n) {
case 1:
NSLog(#"");
NSString *aStr;
break;
default:
break;
}
this compiles with error and it's only missing the NSLog():
switch (n) {
case 1:
NSString *aStr;
break;
default:
break;
}
it throws an error at compile "Expected expression before 'NSString'"
Am I missing something here?
In normal C you'd have to enclose this in brackets in both cases. I suspect this may fix your problem:
case 1:
{
NSLog(#"");
NSString *aStr;
break;
}
See this SO question for more info.
Another way to get around this problem is to put a statement between the case label and the first declaration as you've done in your working example above. See the comments and Quinn Taylor's answer for more info.
You can't declare a variable as the first statement in a case without brackets, and in many other contexts in C-based languages. See Declaring variables inside a switch statement for details.
case 0: {
Loading my nib file;
break;
}
case 1: {
Loading another nib file;
break;
}
Note that if you don't have an assignment (x = y) right after the case it won't be a problem. For example: