在 Objective-C 中将消息发送到 nil

作为一个正在阅读苹果的 Objective-C 2.0文档的 Java 开发人员: 我想知道“ 发送消息到零”是什么意思——更不用说它实际上是如何有用的了。以下是文件摘录:

Cocoa 有几种模式 利用这一事实 从消息返回的值为零 也可能是有效的:

  • 如果该方法返回一个对象、任何指针类型、任何整数标量 尺寸小于或等于 Sizeof (void *)、 float、 double、 a 长的双倍,或者长的长的,然后一个 发送到 nil 的消息返回0。
  • 如果该方法返回由 MacOSXABI 函数定义的 struct 打电话叫导游回来 寄存器,然后发送一条消息到 nil 中的每个字段返回0.0 数据结构。其他结构数据 类型不会用零填充。
  • 如果该方法返回上述值以外的任何值 键入消息的返回值 发送到空是未定义的。

Java 是否让我的大脑无法理解上面的解释?还是我错过了什么能让这一切如玻璃般清晰?

我确实在 Objective-C 中得到了消息/接收者的概念,我只是对碰巧是 nil的接收者感到困惑。

50924 次浏览

What it means is that the runtime doesn't produce an error when objc_msgSend is called on the nil pointer; instead it returns some (often useful) value. Messages that might have a side effect do nothing.

It's useful because most of the default values are more appropriate than an error. For example:

[someNullNSArrayReference count] => 0

I.e., nil appears to be the empty array. Hiding a nil NSView reference does nothing. Handy, eh?

Well, I think it can be described using a very contrived example. Let's say you have a method in Java which prints out all of the elements in an ArrayList:

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

Now, if you call that method like so: someObject.foo(NULL); you're going to probably get a NullPointerException when it tries to access list, in this case in the call to list.size(); Now, you'd probably never call someObject.foo(NULL) with the NULL value like that. However, you may have gotten your ArrayList from a method which returns NULL if it runs into some error generating the ArrayList like someObject.foo(otherObject.getArrayList());

Of course, you'll also have problems if you do something like this:

ArrayList list = NULL;
list.size();

Now, in Objective-C, we have the equivalent method:

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

Now, if we have the following code:

[someObject foo:nil];

we have the same situation in which Java will produce a NullPointerException. The nil object will be accessed first at [anArray count] However, instead of throwing a NullPointerException, Objective-C will simply return 0 in accordance with the rules above, so the loop will not run. However, if we set the loop to run a set number of times, then we're first sending a message to anArray at [anArray objectAtIndex:i]; This will also return 0, but since objectAtIndex: returns a pointer, and a pointer to 0 is nil/NULL, NSLog will be passed nil each time through the loop. (Although NSLog is a function and not a method, it prints out (null) if passed a nil NSString.

In some cases it's nicer to have a NullPointerException, since you can tell right away that something is wrong with the program, but unless you catch the exception, the program will crash. (In C, trying to dereference NULL in this way causes the program to crash.) In Objective-C, it instead just causes possibly incorrect run-time behavior. However, if you have a method that doesn't break if it returns 0/nil/NULL/a zeroed struct, then this saves you from having to check to make sure the object or parameters are nil.

It means often not having to check for nil objects everywhere for safety - particularly:

[someVariable release];

or, as noted, various count and length methods all return 0 when you've got a nil value, so you do not have to add extra checks for nil all over:

if ( [myString length] > 0 )

or this:

return [myArray count]; // say for number of rows in a table

Don't think about "the receiver being nil"; I agree, that is pretty weird. If you're sending a message to nil, there is no receiver. You're just sending a message to nothing.

How to deal with that is a philosophical difference between Java and Objective-C: in Java, that's an error; in Objective-C, it is a no-op.

In the quotation from the documentation, there are two separate concepts -- perhaps it might be better if the documentation made that more clear:

There are several patterns in Cocoa that take advantage of this fact.

The value returned from a message to nil may also be valid:

The former is probably more relevant here: typically being able to send messages to nil makes code more straightforward -- you don't have to check for null values everywhere. The canonical example is probably the accessor method:

- (void)setValue:(MyClass *)newValue {
if (value != newValue) {
[value release];
value = [newValue retain];
}
}

If sending messages to nil were not valid, this method would be more complex -- you'd have to have two additional checks to ensure value and newValue are not nil before sending them messages.

The latter point (that values returned from a message to nil are also typically valid), though, adds a multiplier effect to the former. For example:

if ([myArray count] > 0) {
// do something...
}

This code again doesn't require a check for nil values, and flows naturally...

All this said, the additional flexibility that being able to send messages to nil does come at some cost. There is the possibility that you will at some stage write code that fails in a peculiar way because you didn't take into account the possibility that a value might be nil.

A message to nil does nothing and returns nil, Nil, NULL, 0, or 0.0.

All of the other posts are correct, but maybe it's the concept that's the thing important here.

In Objective-C method calls, any object reference that can accept a selector is a valid target for that selector.

This saves a LOT of "is the target object of type X?" code - as long as the receiving object implements the selector, it makes absolutely no difference what class it is! nil is an NSObject that accepts any selector - it just doesn't do anything. This eliminates a lot of "check for nil, don't send the message if true" code as well. (The "if it accepts it, it implements it" concept is also what allows you to create protocols, which are sorta kinda like Java interfaces: a declaration that if a class implements the stated methods, then it conforms to the protocol.)

The reason for this is to eliminate monkey code that doesn't do anything except keep the compiler happy. Yes, you get the overhead of one more method call, but you save programmer time, which is a far more expensive resource than CPU time. In addition, you're eliminating more code and more conditional complexity from your application.

Clarifying for downvoters: you may think this is not a good way to go, but it's how the language is implemented, and it's the recommended programming idiom in Objective-C (see the Stanford iPhone programming lectures).

ObjC messages which are sent to nil and whose return values have size larger than sizeof(void*) produce undefined values on PowerPC processors. In addition to that, these messages cause undefined values to be returned in fields of structs whose size is larger than 8 bytes on Intel processors as well. Vincent Gable has described this nicely in his blog post

I don't think any of the other answers have mentioned this clearly: if you're used to Java, you should keep in mind that while Objective-C on Mac OS X has exception handling support, it's an optional language feature that can be turned on/off with a compiler flag. My guess is that this design of "sending messages to nil is safe" predates the inclusion of exception handling support in the language and was done with a similar goal in mind: methods can return nil to indicate errors, and since sending a message to nil usually returns nil in turn, this allows the error indication to propagate through your code so you don't have to check for it at every single message. You only have to check for it at points where it matters. I personally think exception propagation&handling is a better way to address this goal, but not everyone may agree with that. (On the other hand, I for example don't like Java's requirement on you having to declare what exceptions a method may throw, which often forces you to syntactically propagate exception declarations throughout your code; but that's another discussion.)

I've posted a similar, but longer, answer to the related question "Is asserting that every object creation succeeded necessary in Objective C?" if you want more details.

From Greg Parker's site:

If running LLVM Compiler 3.0 (Xcode 4.2) or later

Messages to nil with return type | return
Integers up to 64 bits           | 0
Floating-point up to long double | 0.0
Pointers                         | nil
Structs                          | {0}
Any _Complex type                | {0, 0}

C represents nothing as 0 for primitive values, and NULL for pointers (which is equivalent to 0 in a pointer context).

Objective-C builds on C's representation of nothing by adding nil. nil is an object pointer to nothing. Although semantically distinct from NULL, they are technically equivalent to one another.

Newly-alloc'd NSObjects start life with their contents set to 0. This means that all pointers that object has to other objects begin as nil, so it's unnecessary to, for instance, set self.(association) = nil in init methods.

The most notable behavior of nil, though, is that it can have messages sent to it.

In other languages, like C++ (or Java), this would crash your program, but in Objective-C, invoking a method on nil returns a zero value. This greatly simplifies expressions, as it obviates the need to check for nil before doing anything:

// For example, this expression...
if (name != nil && [name isEqualToString:@"Steve"]) { ... }


// ...can be simplified to:
if ([name isEqualToString:@"Steve"]) { ... }

Being aware of how nil works in Objective-C allows this convenience to be a feature, and not a lurking bug in your application. Make sure to guard against cases where nil values are unwanted, either by checking and returning early to fail silently, or adding a NSParameterAssert to throw an exception.

Source: http://nshipster.com/nil/ https://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocObjectsClasses.html (Sending Message to nil).