Reputation: 411
I m taking a NSMutabledictionary object in NSString like this :
NSString *state=[d valueForKey:@"State"];
Now sometimes state may be null and sometimes filled with text.So Im comparing it.While comparing state becomes NSString sometimes and NSCFString othertimes..So unable to get the desired result..
if([state isEqualToString@""])
{
//do something
}
else
{
//do something
}
So while comparing it is returning nil sometimes.So immediately jumping into the else block.
I need a standard way to compare if the state is empty whether it is a NSString or NSCFString ...
How can I do it?
Upvotes: 2
Views: 3694
Reputation: 31091
You can do this
if([state isEqualToString:@""])
{
//do something
}
else
{
//do something
}
Upvotes: 1
Reputation: 3580
You must have to type cast it to get the correct answer.
NSString *state = (NSString *) [d valueForKey:@"State"];
if(state != nil)
{
if(state.length > 0)
{
//string contains characters
}
}
Upvotes: -1
Reputation: 138261
If you're unable to get the result you want, I can assure you it's not because you get a NSCFString
instead of a NSString
.
In Objective-C, the framework is filled with cluster classes; that is, you see a class in the documentation, and in fact, it's just an interface. The framework has instead its own implementations of these classes. For instance, as you noted, the NSString
class is often represented by the NSCFString
class instead; and there are a few others, like NSConstantString
and NSPathStore2
, that are in fact subclasses of NSString
, and that will behave just like you expect.
Your issue, from what I see...
Now sometimes state may be null and sometimes filled with text.
... is that in Objective-C, it's legal to call a method on nil
. (Nil
is the Objective-C concept of null
in other languages like C# and Java.) However, when you do, the return value is always zeroed; so if you string is nil
, any equality comparison to it made with a method will return NO
, even if you compare against nil
. And even then, please note that an empty string is not the same thing as nil
, since nil
can be seen as the absence of anything. An empty string doesn't have characters, but hey, at least it's there. nil
means there's nothing.
So instead of using a method to compare state
to an empty string, you probably need to check that state
is not nil
, using simple pointer equality.
if(state == nil)
{
//do something
}
else
{
//do something
}
Upvotes: 2