简体   繁体   中英

Objective-C Type Error Between value from Core Data

I have one table in my Core Data with one field called userId it is an integer.

I successfully fetched it and assigned it to an id with the following code:

id userId2 = [info valueForKey:@"userId"];

info is my NSManagedObject and userId2 is an id. Now I want to convert userId2 to a string. I read that I can directly do the following:

NSString *userId3 = userId2;

However, when I perform an if check between a string and userId3, even if they have the same value, check fails.

One more thing, Xcode says userId is not a CFString in the debug mode.


My solution was converting both variables into double by:

double myDouble = [userId3 doubleValue];

Any other suggestions?

If userId field is number, it's not NSString , but NSNumber . For this simple case you can use ...

NSString *userId3 = [userId2 stringValue];

... or ...

NSString *userId3 = [NSString stringWithFormat:@"%d", [userId2 intValue]];

... and string comparison should be done in this way ...

if ( [str1 isEqualToString:str2] ) {
}

NSString is a lovely class, there are so much available within the documentation, particularly when you want to display numbers as NSStrings,

If you are not familiar with the likes of NSNumber, NSDecimalNumber, etc I would seriously play around with that, when it comes to int, float and doubles and then dealing with NSNumber + NSDecimalNumber it gets a bit confusing.

I would recommend 'nipping that in the bud' sooner rather than later!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM