1. 他们不是包装类
从系统文件中查看NSInteger和NSUInteger的定义代码如下:
#if __LP__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
为了更好的兼容不同的平台,当程序需要定义整型变量时,建议使用NSInteger和NSUInteger。
#if defined(__LP__) && __LP__
# define CGFLOAT_TYPE double
# define CGFLOAT_IS_DOUBLE 1
# define CGFLOAT_MIN DBL_MIN
# define CGFLOAT_MAX DBL_MAX
#else
# define CGFLOAT_TYPE float
# define CGFLOAT_IS_DOUBLE 0
# define CGFLOAT_MIN FLT_MIN
# define CGFLOAT_MAX FLT_MAX
#endif
/* Definition of the 'CGFloat' type and 'CGFLOAT_DEFINED'.*/
typedef CGFLOAT_TYPE CGFLoat;
#define CGFLOAT_DEFINED 1
为了更好的兼容不同的平台,当程序需要定义浮点型变量时,建议使用CGFloat。
2. NSValue和NSNumber
NSValue和NSNumber都湿包装类,其中NSValue是NSNumber的父类;NSValue是一个通用的包装类,他可以包装单个short、int、long、float、char、指针、对象id等数据项,通过包装类,就可以把他们添加到NSArray、NSSet等集合(他们的元素必须是对象)中。
NSNumber是更具体的包装类,主要用于包装C语言的各种数据类型。它包括如下3类方法
+ numberWithXxx: 该类方法直接将特定类型的值包装成NSNumber。
- initWithXxx: 该实例方法需要先创建一个NSNumber对象,再用一个基本类型的值来初始化NSNumber。
- xxxValue: 该实例方法返回该NSNumber对象包装的基本类型的值。
下面的程序示范了基本类型的值与包装类之间的转换。
int main(void) {
@autoreleasepool {
// 调用类方法将int类型的值包装成NSNumber对象
NSNumber* num = [NSNumber numberWithInt:20];
// 调用类方法将double类型的值包装成NSNumber对象
NSNumber* de = [NSNumber numberWithDouble:3.14];
NSLog(@"%d", [num intValue]);
NSLog(@"%g", [de doubleValue]);
// 先创建NSNumber对象,在调用initWithXxx方法初始化
NSNumber* ch = [[NSNumber alloc] initWithChar:'J'];
NSLog(@"%c", [ch charValue]);
}
}
输出:
2022-05-25 19:47:18.054607+0800 oc.programme[83382:2921211] 20
2022-05-25 19:47:18.054824+0800 oc.programme[83382:2921211] 3.14
2022-05-25 19:47:18.054846+0800 oc.programme[83382:2921211] J
Program ended with exit code: 0
3. description方法
description方法是NSObject的一个实例方法,所有的Objective-C对象都有description方法。
重写description方法通常返回如下格式的字符串:
<类名[实例变量1 = 值1, 实例变量2 = 值2, ...]>
例:
#import <Foundation/Foundation.h>
@interface FKApple : NSObject
@property (nonatomic, copy) NSString* color;
@property (nonatomic, assign) double weight;
- (id) initWithColor:(NSString*) color andWeight:(double) weight;
@end
@implementation FKApple
- (id) initWithColor:(NSString*) color andWeight:(double)weight {
if (self = [super init]) {
self.color = color;
self.weight = weight;
}
return self;
}
// 重写dascription方法
- (NSString*) description {
return [NSString stringWithFormat:@"<FKApple [_color = %@, _weight = %g]>", self.color, self.weight];
}
@end
int main(void) {
@autoreleasepool {
FKApple* apple = [[FKApple alloc] initWithColor:@"red" andWeight:3.4];
NSLog(@"%@", [apple description]);
}
}
输出:
2022-05-25 20:17:26.728582+0800 oc.programme[83772:2934653] <FKApple [_color = red, _weight = 3.4]>
Program ended with exit code: 0