我正在尝试比较id对象的类。但是,如果我尝试将对象的类与NSNumber的类进行比较,即使我已经将一些变量设置为NSNumber,它也不会注册为等于。请告诉我它为什么没有注册,这是我的代码。
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject: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:@"}"];
答案 0 :(得分:0)
使用:if([obj isKindOfClass:[NSNumber class]])...
答案 1 :(得分:0)
这是因为NSNumber是一个集群类,当你创建一个NSNumber实例时,你实际上得到了一个子类的实例。正如ott所说,你应该使用isKindOfClass:。