在未初始化的对象(空指针)上调用方法 [英] Calling a method on an uninitialized object (null pointer)

查看:22
本文介绍了在未初始化的对象(空指针)上调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 如果你在一个对象(指针)上调用一个 nil 方法(可能是因为有人忘记初始化它),那么在 Objective-C 中的正常行为是什么?它不应该产生某种错误(分段错误,空指针异常......)吗?
  2. 如果这是正常行为,有没有办法改变这种行为(通过配置编译器),以便程序在运行时引发某种错误/异常?

为了更清楚我在说什么,这里有一个例子.

To make it more clear what I am talking about, here's an example.

有这个课程:

@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

在程序的某个地方我这样做:

Somewhere in the program I do this:

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 中是完全可以接受的,它被视为无操作.没有办法将其标记为错误,因为它不是错误,实际上它可能是该语言的一个非常有用的特性.

A message sent to a nil object is perfectly acceptable in Objective-C, it's treated as a no-op. There is no way to flag it as an error because it's not an error, in fact it can be a very useful feature of the language.

来自 文档:

向 nil 发送消息

在 Objective-C 中,发送一个给 nil 的消息——它根本没有效果在运行时.有几种模式在 Cocoa 中利用这一点事实.从 a 返回的值发给 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:

  • 如果方法返回一个对象,那么发送给 nil 的消息返回0(nil),例如:

  • If the method returns an object, then a message sent to nil returns 0 (nil), for example:

Person *motherInLaw = [[aPerson 配偶] 母亲];

如果 aPersonspousenil,然后 mother 被发送到 nil 并且方法返回 nil.

If aPerson’s spouse is nil, then mother is sent to nil and the method returns nil.

如果方法返回任何指针类型,任何大小小于的整数标量大于或等于 sizeof(void*),一个float,一个 double,一个 long double,或 long long,然后发送一条消息到 nil 返回 0.

If the method returns 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.

如果方法返回一个 struct,由 Mac OS X ABI 定义要返回的函数调用指南注册,然后将消息发送到nil 为每个字段返回 0.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.

如果方法返回的不是上述值类型消息的返回值发送到 nil 是未定义的.

If the method returns anything other than the aforementioned value types the return value of a message sent to nil is undefined.

这篇关于在未初始化的对象(空指针)上调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆