-
Notifications
You must be signed in to change notification settings - Fork 0
/
NSObjectExtension.m
94 lines (67 loc) · 1.89 KB
/
NSObjectExtension.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//
// NSObjectExtension.m
//
// Licensed by ruralcoder.com under the
// Creative Commons Attribution-ShareAlike 3.0 Unported License
#import "NSObjectExtension.h"
#import "NSDateExtension.h"
@implementation NSObject (Extension)
- (DataType) dataType
{
if (self == nil) return DataTypeNil;
// STRING - just return it back
if ([self isKindOfClass:[NSString class]])
return DataTypeString;
if ([self isKindOfClass:[NSData class]])
return DataTypeData;
if ([self isKindOfClass:[NSDate class]])
return DataTypeDate;
if ([self isKindOfClass:[NSArray class]])
return DataTypeArray;
if ([self isKindOfClass:[NSDictionary class]])
return DataTypeDictionary;
if ([self isKindOfClass:[NSNumber class]])
{
NSNumber *number = (NSNumber*) self;
const char *type = [number objCType];
if (*type == 'c' && [number respondsToSelector:@selector(boolValue)])
return DataTypeBoolean;
else
return DataTypeNumeric;
}
return DataTypeObject;
}
- (NSString*) toString
{
if (self == nil)
return @"n/a";
// STRING - just return it back
if ([self isKindOfClass:[NSString class]])
return (NSString*) self;
// DATE - format it first
if ([self isKindOfClass:[NSDate class]])
{
NSDate *date = (NSDate*) self;
return [date toString];
}
// NUMBER - might be a BOOL, INT or FLOAT
if ([self isKindOfClass:[NSNumber class]])
{
NSNumber *number = (NSNumber*) self;
const char *type = [number objCType];
if (*type == 'c')
{
if ([number respondsToSelector:@selector(boolValue)])
return ([number boolValue] == YES) ? @"Yes" : @"No";
}
if (*type == 'f')
{
if ([number respondsToSelector:@selector(floatValue)])
return [NSString stringWithFormat:@"%1.1f", [number floatValue]];
}
if ([number respondsToSelector:@selector(integerValue)])
return [NSString stringWithFormat:@"%d", [number integerValue]];
}
return [self description];
}
@end