Search code examples
iosnsstringfoundationnsobjectnsdecimalnumber

Can NSString be treated as a NSCFDecimal?


I wanted to compare two strings using - (BOOL)isEqualToString:(NSString *)aString These strings are objects from a dictionary using -(id)objectForKey:(id)aKey containing numerical characters.

When I check the classes of these strings using [object class], no matter how I casted them to be NSString *, it keeps showing that they are NSCFDecimal number, requiring to be compared using ==. If I wanted to use isEqualToString on them, it throws error.

Can anyone explain why this is happening?


Solution

  • Objective-C is highly dynamic language. It's no matter what type of variable you declare, only runtime matters. For example:

    NSString *str = [NSNumber numberWithInt:5];
    

    str - is NSNumber.

    If you want to compare NSInteger (for exmaple) with string you should do like this:

    NSInteger num = 9;
    NSString *stringWithNumber = [NSString stringWithFormat:@"%d", num];
    if ([stringWithNumber isEqualToString:yourString])
    { ... }