黑马程序员技术交流社区

标题: 两个 NSNumber 方法谁能给我解释一下 [打印本页]

作者: guozihui876    时间: 2015-10-28 21:56
标题: 两个 NSNumber 方法谁能给我解释一下
- (NSNumber *)initWithInt:(int)value NS_DESIGNATED_INITIALIZER;
+ (NSNumber *)numberWithInt:(int)value;

这两个方法 求好心人帮忙解释一下 , 最好举例说明
作者: guozihui876    时间: 2015-10-29 00:01
{:2_31:}{:2_31:}{:2_31:}{:2_31:}{:2_31:}{:2_31:}
作者: wwf707542865    时间: 2015-10-29 00:03
本帖最后由 wwf707542865 于 2015-10-29 00:09 编辑

一个是对象方法
  NSNumber *IntNum2 = [[NSNumber alloc]initWithInt:10];//这里要先有对象,所以是 [NSNumber alloc]对象调用这个方法
一个是类方法
NSNumber *IntNum1 = [NSNumber numberWithInt:20];//直接是NSNumber这个类调用方法
NS_DESIGNATED_INITIALIZER这个是宏定义,请原谅我小学英语是体育老师教得,自己看文档吧,如下
The designated initializer guarantees the object is fully initialised by sending an initialization message to the superclass. The implementation detail becomes important to a user of the class when they subclass it. The rules for designated initializers in detail:

A designated initializer must call (via super) a designated initializer of the superclass. Where NSObject is the superclass this is just [super init].
Any convenience initializer must call another initializer in the class - which eventually leads to a designated initializer.
A class with designated initializers must implement all of the designated initializers of the superclass.
As an example, if your interface is

@interface MyClass : NSObject
@property(copy, nonatomic) NSString *name;
-(instancetype)initWithName:(NSString *)name NS_DESIGNATED_INITIALIZER;
-(instancetype)init;
@end
then the compiler checks if the (convenience) initializer init calls the (designated) initializer initWithName:, so this would cause a warning:

-(instancetype)init
{
    self = [super init];
    return self;
}
and this would be OK:

-(instancetype)init
{
    self = [self initWithName:@""];
    return self;
}
In Swift the rules about designated and convenience initializers are even more strict, and if you mix Objective-C and Swift code, marking the designated Objective-C initializers helps the compiler to enforce the rules.

For example, this Swift subclass would cause an compiler error:

class SwClass: MyClass {
    var foo : String
    init(foo : String) {
        self.foo = foo
        super.init()
    }
}
and this would be OK:

class SwClass: MyClass {
    var foo : String
    init(foo : String) {
        self.foo = foo
        super.init(name: "")
    }
}

作者: kingwang    时间: 2015-10-29 00:15
下面的回答很全啊




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2