- 如果您在一个为 nil 的对象(指针)上调用一个方法(可能是因为有人忘记初始化它),那么在 Objective-C 中的正常行为是什么?它不应该产生某种错误(段错误、空指针异常……)吗?
- 如果这是正常行为,是否有一种方法可以改变这种行为(通过配置编译器),以便程序在运行时引发某种错误/异常?
为了更清楚地说明我在说什么,这里有一个例子。
有这门课:
@interface Person : NSObject {
NSString *name;
}
@property (nonatomic, retain) NSString *name;
- (void)sayHi;
@end
使用此实现:
@implementation Person
@synthesize name;
- (void)dealloc {
[name release];
[super dealloc];
}
- (void)sayHi {
NSLog(@"Hello");
NSLog(@"My name is %@.", name);
}
@end
我在程序的某个地方这样做:
Person *person = nil;
//person = [[Person alloc] init]; // let's say I comment this line
person.name = @"Mike"; // shouldn't I get an error here?
[person sayHi]; // and here
[person release]; // and here
最佳答案
发送到 nil
对象的消息在 Objective-C 中是完全可以接受的,它被视为空操作。无法将其标记为错误,因为它不是错误,事实上它可能是该语言的一个非常有用的功能。
来自docs :
Sending Messages to nil
In Objective-C, it is valid to send a message to nil—it simply has no effect at runtime. 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, then a message sent to
nil
returns0
(nil
), for example:
Person *motherInLaw = [[aPerson spouse] mother];
If
aPerson
’sspouse
isnil
, thenmother
is sent tonil
and the method returnsnil
.If the method returns any pointer type, any integer scalar of size less than or equal to
sizeof(void*)
, afloat
, adouble
, along double
, or along long
, then a message sent tonil
returns0
.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 tonil
returns0.0
for every field in the data structure. Otherstruct
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.
关于iphone - 在未初始化的对象(空指针)上调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2696891/