objective-c - 在 Objective-C 中向 nil 发送消息

作为一名正在阅读 Apple 的 Objective-C 2.0 文档的 Java 开发人员:我想知道“向 nil 发送消息”是什么意思——更不用说它的实际用途了。从文档中摘录:

There are several patterns in Cocoa that take advantage of this fact. The value returned from a message to nil may also be valid:

  • If the method returns an object, any pointer type, any integer scalar of size less than or equal to sizeof(void*), a float, a double, a long double, or a long long, then a message sent to nil returns 0.
  • If the method returns a struct, as defined by the Mac OS X ABI Function Call Guide to be returned in registers, then a message sent to nil returns 0.0 for every field in the data structure. Other struct data types will not be filled with zeros.
  • If the method returns anything other than the aforementioned value types the return value of a message sent to nil is undefined.

Java 是否让我的大脑无法理解上面的解释?或者有什么我遗漏的东西可以使它像玻璃一样清晰?

我确实了解 Objective-C 中的消息/接收器的概念,我只是对恰好为 nil 的接收器感到困惑。

最佳答案

嗯,我认为可以用一个非常人为的例子来描述它。假设您在 Java 中有一个方法可以打印出 ArrayList 中的所有元素:

void foo(ArrayList list)
{
    for(int i = 0; i < list.size(); ++i){
        System.out.println(list.get(i).toString());
    }
}

现在,如果您像这样调用该方法: someObject.foo(NULL);当它试图访问列表时,你可能会得到一个 NullPointerException,在这种情况下是调用 list.size();现在,您可能永远不会使用这样的 NULL 值调用 someObject.foo(NULL) 。但是,如果在生成 ArrayList 时遇到一些错误,例如 someObject.foo(otherObject.getArrayList());

当然,如果你这样做,你也会遇到问题:

ArrayList list = NULL;
list.size();

现在,在 Objective-C 中,我们有等效的方法:

- (void)foo:(NSArray*)anArray
{
    int i;
    for(i = 0; i < [anArray count]; ++i){
        NSLog(@"%@", [[anArray objectAtIndex:i] stringValue];
    }
}

现在,如果我们有以下代码:

[someObject foo:nil];

我们遇到同样的情况,Java 会产生 NullPointerException。 nil 对象将首先在 [anArray count] 处被访问。但是,Objective-C 不会抛出 NullPointerException,而是按照上面的规则简单地返回 0,因此循环不会运行。但是,如果我们将循环设置为运行一定次数,那么我们首先在 [anArray objectAtIndex:i] 处向 anArray 发送消息;这也将返回 0,但是由于 objectAtIndex: 返回一个指针,并且指向 0 的指针是 nil/NULL,因此 NSLog 每次循环都会传递 nil。 (虽然 NSLog 是一个函数而不是一个方法,但如果传递一个 nil NSString,它会打印出 (null)。

在某些情况下,最好有一个 NullPointerException,因为您可以立即判断程序有问题,但除非您捕获该异常,否则程序将崩溃。 (在 C 中,尝试以这种方式取消引用 NULL 会导致程序崩溃。)在 Objective-C 中,它只会导致可能不正确的运行时行为。但是,如果您有一个在返回 0/nil/NULL/零结构时不会中断的方法,那么您就不必检查以确保对象或参数为 nil。

https://stackoverflow.com/questions/156395/

相关文章:

objective-c - 如何将 NSTimeInterval(秒)转换为分钟

iphone - 代码设计错误 : Certificate identity appearing t

ios - 添加一个简单的 UIAlertView

objective-c - 从当前日期减去 7 天

ios - 检测到约束模糊地表明高度为零的情况

ios - 从 iPhone 上的 NSString 中删除 HTML 标签

ios - 如果没有 Table View 结果,在屏幕上显示 "No Results"

objective-c - Objective-C 中 `oneway void` 的用例?

ios - 如何以编程方式检查 iOS 应用程序中是否存在键盘?

iphone - ${EXECUTABLE_NAME} 和 ${PRODUCT_NAME} 在哪里定