iphone - 在未初始化的对象(空指针)上调用方法

标签 iphone objective-c initialization null-pointer

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

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

有这门课:

@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 returns 0 (nil), for example:

    Person *motherInLaw = [[aPerson spouse] mother];

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

  • 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.

  • 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.

关于iphone - 在未初始化的对象(空指针)上调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2696891/

相关文章:

iphone - 在后台轮询服务器的正确方法

ios - 检查 Motion&Fitness 选项在设置中是否可用

ios - 'AppDelegate' 没有可见的@interface 声明选择器 'displayMessage'

ios - 更改 HeaderInSection 的 UITableView 高度?

c++ - 如何使用 std::array 模拟 C 数组初始化 "int arr[] = { e1, e2, e3, ... }"行为?

iphone - 将凭证保存到 iPhone 钥匙串(keychain)中的教程?

iphone - UIScrollView - 为新的 contentSize 设置适当的 contentOffset 会产生不需要的空白空间

iphone - 获取地址簿数据,它的代码在模拟器上运行但没有运行 iPhone 设备。

c++ - C++类中的两种不同的变量初始化。有什么不同?

swift - Swift语言初始化