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

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

问题描述


  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

我在节目的某处这个:

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


推荐答案

发送给<$的消息c $ c> 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.

来自 docs


发送消息为零

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

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

如果 aPerson 配偶 nil
然后母亲被发送到 nil
方法返回 nil

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

如果方法返回任何指针类型,则任何大小较小的整数标量
大于或等于 sizeof(void *)
float 长双
长多,然后发送消息
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
函数调用指南的定义返回i n
注册,然后发送到
的消息 nil 为$中的每个字段返回 0.0 b $ b数据结构。其他 struct
数据类型不会用
零填充。

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天全站免登陆