NSString or NSCFString in xcode?

I accept an NSMutabledictionary object in an NSString as follows:

NSString *state=[d valueForKey:@"State"]; 

Now sometimes the state can be zero, and sometimes filled with text. So I compare it. If a state comparison becomes NSString sometimes, and NSCFString othertimes..So is unable to get the desired result.

 if([state isEqualToString@ ""]) { //do something } else { //do something } 

Therefore, comparing this, nil sometimes returns. It also immediately jumps to the else block.

I need a standard way of comparing if the state is empty, be it NSString or NSCFString ...

How can i do this?

+2
source share
3 answers

If you cannot get the desired result, I can assure you that this is not because you will get NSCFString instead of NSString .

In Objective-C, a structure is populated with cluster classes; that is, you see the class in the documentation, but in fact it is just an interface. This framework has its own implementations of these classes. For example, as you noted, the NSString class is often represented by the NSCFString class; and there are several others, such as NSConstantString and NSPathStore2 , which are actually subclasses of NSString , and will behave as you expect.

Your problem, from what I see ...

Now sometimes the state can be zero and sometimes filled with text.

... is that in Objective-C it is allowed to call a method on nil . ( nil is the concept of Objective-C null in other languages ​​such as C # and Java.) However, when you do this, the return value is always nullified; therefore, if the string is nil , any equality comparison made using the method will return NO , even if you compare it to nil . And even then, note that an empty string is not the same as nil , since nil can be thought of as the absence of anything. The empty string has no characters, but hey, at least there. nil doesn't mean anything.

Therefore, instead of using the method to compare state with an empty string, you probably need to check that state not nil using simple pointer equality.

 if(state == nil) { //do something } else { //do something } 
+2
source

You can do it

 if([state isEqualToString:@""]) { //do something } else { //do something } 
+1
source

You need to type the text to get the correct answer.

  NSString *state = (NSString *) [d valueForKey:@"State"]; if(state != nil) { if(state.length > 0) { //string contains characters } } 
-1
source

All Articles