stringWithFormat: with unknown datatype
I am making a framework and I have this code (conditions
is an NSDictionary):
for (NSString *key in conditions) {
id value = [[conditions valueForKey:key] retain];
// Check if number or string
if ([value class] == [NSString class]) {
conditionsString = [NSString stringWithFormat:@"%@='%@' ", key, value];
} else {
conditionsString = [NS开发者_运维知识库String stringWithFormat:@"%@=%@ ", key, value];
}
}
If the value
is an NSString, quotes should be added, otherwise codes should not be added. However, if not an NSString, I don't know the datatype of value
, as it could be NSNumber, NSInteger, int, float, double, etc... I can't just use %@
or %d
but I'm sure someone on SO knows how to do this? Thanks.
have a look at this.
edit: in your case it's pretty easy, since nsdictionary can only contain nsobjects. so %@ would do the trick.
You could check the class (kindOfClass) and then use appropriate formatter.
e.g.
if ( [myObj isKindOfClass:[NSString class]] )
精彩评论