- 如果您在對象(指針)上調用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
而且我不知道有任何的方式來改變這種行爲。這是使用Objective-C/Cocoa進行編程的基本部分。你會學會去愛它。 – 2010-04-23 07:47:38
鏈接到doc中的答案已死(*找不到頁*)。 – Pang 2016-12-07 09:19:04