NSNmuber
因为NSArray和NSDictionary只能储存对象,而不能直接储存任何基本类型的数据,如int、float和struct。
Cocoa提供了NSNumber类来封装基本数据类型。
创建方法
+(NSNumber *) numberWithChar: (char) value;
+(NSNumber *) numberWithInt: (Int) value;
+(NSNumber *) numberWithFloat: (float) value;
+(NSNumber *) numberWithBool: (BOOL) value;
也可以使用以下的创建方法
NSNumber *number;
number = @'X';//字符型
number = @12345;//整型
number = @12345ul;//无符号长整形
number = @12345ll;//long long
number = @123.45;//浮点型
number = @YES;//布尔值
添加到字典或数组
NSNumber *number = @42;
[array addObject number];
[dictionary setObject:number forKey:@"Bork"];
提取方法
将一个数据封装到NSNumber中后,可以通过以下的实例方法重新获得它
-(char) charValue;
-(int) intValue;
-(float) floatValue;
-(BOOL) boolValue;
-(NString *) stringvalue;
NSValue
封装
NSnumber其实是NSValue的子类,NSValue可以封装任意值。可以使用NSValue将结构体放入NSArray或NSDictionary中
+(NSValue *) valueWithBytes: (const void *) value objCType: (const char *) type;
NSRect rect = NSMakeRect(1,2,30,40);
NSValue *value = [NSValue valueWithByte:&rect objCType:@encode(NSRect)];
[array addObject:value];
提取
-(void)getValue:(void *)buffer;
可以使用getValue:方法提取数值
value = [array objectAtIndex: 0];
[value getValue:&rect]
便捷方法
+ (NSValue *)valueWithPoint:(NSPoint)aPoint;
+ (NSValue *)valueWithSize:(NSSize)Size;
+ (NSValue *)valueWithRect:(NSRect)rect;
- (NSPoint)pointValue;
- (NSSize)sizeValue;
- (NSRect)rectValue;
在NSArray中储存和提取NSRect值:
value = [NSValue valueWithRect:rect];
[array addObject:value];
...
NSRect anotherRect = [value rectValue];
NSNull
因为集合中不能放nil值,但如果想需要储存一个表示“什么都没有”的值。
+ (NSNull *) null;
添加到集合
[contact setObject: [NSNull null] forKey:@"home fax machine"];
访问的方式
id homefax = [contact objectForKey:@"home fax machine"]
if(homefax == [NSNull null])
{
//....确定没有传真机
}