• objective-c之各种数值


    各种数值

    NSArray和NSDictionary都只能存储对象,不能存储任何基本类型的数据,如int,float,struct。因此我们可以用对象来封装基本的数值。

    NSNumber

    Cocoa提供了NSNumber来存储对象,但不能存储C里面的各种数据,所以我们要用一些相应的对象来进行封装。

    NSNumber类来包装基本数据对象。可以有下列方法:

    + (NSNumber *) numberWithChar: (char) value;

    + (NSNumber *) numberWithInt: (int) value;

    + (NSNumber *) numberWithFloat: (float) value;

    + (NSNumber *) numberWithBool: (BOOL) value;

    只要将一个基本类型数据封闭到NSNumber中后,就可以通过下面的实例方法重新获得它:

    - (char) charValue:

    - (int) intValue;

    -(float)floatValue;

    - (BOOL)boolValue;

    - (NSString *) stringValue;

     

    NSValue

    NSNumber实际上是NSValue的子类,NSValue可以包装任意值,你可以用NSValue将结构放入NSArray和NSDictionary中,通过下列方法创建新的NSValue:

    + (NSValue *) valueWithBytes:(const void *) values

                    objCType:(constchar*) type;

    传递的参数是你想要包装的数值的地址(如一个NSSize或者你自己的struct)。通常,得到的是你想要存储的变量的地址,你也可以提供一个用来描述这个数据类型的字符串,通常用来说明struct中实体的类型和大小。如下例所示,将NSRect放入到NSArray中:

    NSRect rect = NSMakeRect(1, 2, 30, 40);

    NSValue *value;

    value = [NSValue valueWithBytes: &rect

    objCType: @encode(NSRect)];

    [array addObject: value];

    可以使用getValue:来提供数值:

    - (void) getValue: (void *) vaule;

    调用getValue:时,要传递的是要存储这个数值的变量的地址:

    value = [array objectAtIndex:0];

    [value getValue: &rect];

     

    Cocoa提供了将常用的struct型数据转换成NSValue便捷方法,如下所示:

    + (NSValue*) valueWithPoint:(NSPoint) point;

    + (NSValue*) valueWithSize:(NSSize) size;

    + (NSValue*) valueWithRect:(NSRect) rect;

     

    - (NSPoint) pointValue;

    - (NSSize) sizeValue;

    - (NSRect) rectValue;

    例:

    value = [NSValue valueWithRect:rect];

    [array addObject:value];

    NSRect anotherRect = [value rectValue];

     

    NSNull

    有时确实需要存一个NULL值,而大多数的对象里面是不允许存nil值的,那么使用NSNull就可以解决这个问题。

    + (NSNull *) null;

    例:

    [contact setObject:[NSNull null]

    forKey:@”home fax machine”];

    那么怎么进行访问及判断呢:

    id homefax;

    homefax = [contact objectForKey:@”home fax machine”];

     

    if(homefax == [NSNull null])

    {

    //…no fax machine

    }

  • 相关阅读:
    个人WPF快速入门笔记 基础样式篇02
    个人WPF快速入门笔记 基础布局篇01
    nginx常用笔记备忘
    【leetcode】1685. Sum of Absolute Differences in a Sorted Array
    【leetcode】1696. Jump Game VI
    【leetcode】1694. Reformat Phone Number
    【leetcode】1684. Count the Number of Consistent Strings
    【leetcode】1695. Maximum Erasure Value
    【leetcode】1671. Minimum Number of Removals to Make Mountain Array
    【leetcode】1689. Partitioning Into Minimum Number Of DeciBinary Numbers
  • 原文地址:https://www.cnblogs.com/zxykit/p/5157947.html
Copyright © 2020-2023  润新知