- 如果你在一个 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