以下代码的含义

Ran*_*wan 0 iphone cocoa-touch if-statement

我有一个从网上下载的示例应用程序
在此我无法理解以下代码

UILocalNotification *localNotif = [[UILocalNotification alloc] init];

if (localNotif == nil) 
    return;
Run Code Online (Sandbox Code Playgroud)

  if (!array1) 
        return;
Run Code Online (Sandbox Code Playgroud)

这个代码是否意味着如果对象不存在则返回.....

救命

Abi*_*ern 5

在Cocoa中,如果调用成功,初始化器将返回对象指针,如果无法创建对象,则返回nil.

两种情况都在检查对象的存在.实际上,检查是否存在指向对象的指针,并在对象不存在时简单地返回.作为示例,这是对象的常见初始化形式.

- (id)init  {
    // Call the superclass initialiser first and check that it was successful.
    if (!(self = [super init])) {
        // If the superclass initialiser failed then self will be nil.
        // return a nil because we cannot create this object.
        return nil; // Bail!
    }
    // Do more initialising 
    // If we can initialise the superclass and ourself, return a pointer to ourself
    return self;
}
Run Code Online (Sandbox Code Playgroud)

但是,您提供的代码段不足以判断代码是否正确.例如,如果第一个示例是初始化方法的一部分,则它是不正确的,因为它不返回任何类型的对象.

编辑

从你的进一步例子这两个打印hiiiiiiii

NSArray *arr;
if(arr) { NSLog(@"hiiiiii");
Run Code Online (Sandbox Code Playgroud)

NSArray *arr = [[NSArray alloc]init];
if(arr) { NSLog(@"hiiiiii");
Run Code Online (Sandbox Code Playgroud)

在第一种情况下,您声明arr是指向NSArray的指针,但由于它尚未初始化,因此该指针只是随机数的垃圾值.但它不是nil那么你的if语句评估为真.这并不意味着它是指向NSArray的有效指针.

在第二个示例中,您声明了一个NSArray指针并对其进行初始化.这已成功初始化,因此指针不是nil,if语句的计算结果为true.在这种情况下,您有一个有效的NSArray指针.

声明不是初始化!

也许如果你解释一下你想要做什么,我们就能更好地回答你的问题.