Use of @ encode in Objective-C, objective-c @ encode
Today, when I read Mansonry's code, I came across a rare keyword (maybe I have never used it myself ). :-)
@ Encode => encode a given type as an internal string.
In order to make it easier for you to check it out, you can also write a small example here to learn how to use it.
NSLog (@ "UIViewController: % s", @ encode (UIViewController ));
NSLog (@ "CGRect: % s", @ encode (CGRect ));
NSLog (@ "int: % s", @ encode (int ));
NSLog (@ "float: % s", @ encode (float ));
NSLog (@ "double: % s", @ encode (double ));
NSLog (@ "BOOL: % s", @ encode (BOOL ));
NSLog (@ "long: % s", @ encode (long ));
NSLog (@ "short: % s", @ encode (short ));
NSDictionary * numberDic ={ @ "double": [NSNumber numberWithDouble: 1.00f],
@ "Float": [NSNumber numberWithFloat: 2.0f],
@ "Int": [NSNumber numberWithInt: 2],
@ "Long": [NSNumber numberWithLong: 2],
@ "Bool": [NSNumber numberWithBool: YES],
@ "Short": [NSNumber numberWithShort: 2],
};
For (NSString * key in numberDic ){
NSNumber * value = [numberDic valueForKey: key];
Const char * pObjCType = [value objCType];
If (strcmp (pObjCType, @ encode (double) = 0 ){
NSLog (@ "double: % @", value );
}
If (strcmp (pObjCType, @ encode (float) = 0 ){
NSLog (@ "float: % @", value );
}
If (strcmp (pObjCType, @ encode (int) = 0 ){
NSLog (@ "int: % @", value );
}
If (strcmp (pObjCType, @ encode (long) = 0 ){
NSLog (@ "long: % @", value );
}
If (strcmp (pObjCType, @ encode (bool) = 0 ){
NSLog (@ "bool: % @", value );
}
If (strcmp (pObjCType, @ encode (short) = 0 ){
NSLog (@ "short: % @", value );
}
}
The output of this Code is as follows:
16:18:56. 316 test [1000:251554] UIViewController: {UIViewController = #}
16:18:56. 316 test [1000:251554] CGRect: {CGRect = {CGPoint = dd} {CGSize = dd }}
16:18:56. 316 test [1000:251554] int: I
16:18:56. 316 test [1000:251554] float: f
16:18:56. 316 test [1000:251554] double: d
16:18:56. 317 test [1000:251554] BOOL: B
16:18:56. 317 test [1000:251554] long: q
16:18:56. 317 test [1000:251554] short: s
16:18:57. 268 test [1000:251554] double: 1
16:18:57. 268 test [1000:251554] float: 2
16:18:57. 268 test [1000:251554] int: 2
16:18:57. 268 test [1000:251554] long: 2
16:18:57. 269 test [1000:251554] short: 2
From the above we can see that int is encoded as I; float is f; and so on.
Here is a problem: [NSNumber numberWithBool: YES] When the objCType method is called, "c" instead of "B" is returned ", therefore, the if judgment below does not print the bool-related output. To solve this problem, I made a search. "B" indicates a C ++ bool. In Ojbective-C, BOOL is actually a singned char, therefore, "c" is returned when objCType is called ".