Convert NSCFString to NSString

孤街醉人 提交于 2019-12-07 04:39:37

问题


I am getting a dictionary from server

myDictionary = 
{
"rank":"1",
"color":"red",
"position":"middle"
}

Now I want to check the value of key "position" in if condition

I am doing it like this

if ([[myDictionary valueForKey:@"position"] isEqualToString:@"middle"]) {
        //do Some stuff
} else{
        //do some other stuff
}

but data type of [myDictionary valueForKey:@"position"] is _NSCFString, so it does not compare value properly and never goes in if loop even the value is correct.

how do I convert it into NSString so that I could compare it in if condition ?

I have seen these questions..

NSString instance reports its class as NSCFString

Getting an NSString from an NSCFString

NSString or NSCFString in xcode?

from these question I just came to know that NSString is really a container class for different types of string objects. Generally an NSString constructor does return an object that is actually of type NSCFString, which is a thin wrapper around the Core Foundation CFString struct.

but they didn't help me..and no one actually telling how to convert in into NSString, so please don't mark it as duplicate.


回答1:


You don't need to convert _NSCFString to NSString. As a subclass of NSString it's guaranteed to respond to -isEqualToString: (and every other method in NSString). Your issue is not coming from the string, likely it is coming from myDictionary. Try logging all the keys in the dictionary and make sure it is behaving as expected.




回答2:


CFStrings can be cast to NSStrings as per the docs

NSString is “toll-free bridged” with its Core Foundation counterpart, CFStringRef. See “Toll-Free Bridging” for more information on toll-free bridging.

NSString *nsString = @"Hello";
CFStringRef cfString = (CFStringRef) nsString;

You really want to work out why the values aren't being equal. Separate out your method calls:

NSString *positionValue = myDictionary[@"position"];
NSLog(@"Position value: %@", positionValue);
if ([positionValue isEqualToString:@"middle"]) {
    // do Some stuff
} else{
    // do some other stuff
}


来源:https://stackoverflow.com/questions/23150967/convert-nscfstring-to-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!