开发者

id comparison is not working correctly

I am trying to compare the classes of an id object. However, if I try and compare the object's class to the class of NSNumber, it won't register as equal to, even though I have set some variables to NSNumbers. Please can you tell me why it isn't registering, here is my code.

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObjec开发者_如何学Got:n.title forKey:@"title"];
[dict setObject:[NSNumber numberWithBool:n.allDay] forKey:@"allDay"];
[dict setObject:[NSNumber numberWithInt:n.availability] forKey:@"availability"];
[dict setObject:[NSNumber numberWithInt:n.createdBy] forKey:@"createdBy"];
[dict setObject:n.endDate forKey:@"endDate"];
[dict setObject:n.location forKey:@"location"];
[dict setObject:n.notes forKey:@"notes"];
[dict setObject:n.ownerUsername forKey:@"ownerUsername"];
[dict setObject:n.startDate forKey:@"startDate"];
[dict setObject:[NSNumber numberWithInt:n.status] forKey:@"status"];
NSMutableString *json = [NSMutableString string];
[json appendString:@"{"];
for (NSString *key in [dict allKeys]) {
    id obj = [dict objectForKey:key];
    if ([[dict allKeys] indexOfObject:key] == 0) {
        if ([obj class] == [NSNumber class]) 
            [json appendFormat:@"\"%@\":%@", key, obj];
        else
            [json appendFormat:@"\"%@\":\"%@\"", key, obj];
    }
    else {
        if ([obj class] == [NSNumber class]) 
            [json appendFormat:@",\"%@\":%@", key, obj];
        else
            [json appendFormat:@",\"%@\":\"%@\"", key, obj];
    }
}
[json appendString:@"}"];


Use: if ([obj isKindOfClass:[NSNumber class]]) ...


This is because NSNumber is a cluster class, when you create an instance of NSNumber you actually get a instance of a subclass. As ott said you should use isKindOfClass:.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜