相关疑难解决方法(0)

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

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

为了使我所说的更清楚,这是一个例子.

有这个课程:

@interface Person : NSObject {

    NSString *name;

}

@property (nonatomic, retain) NSString *name;

- (void)sayHi;

@end
Run Code Online (Sandbox Code Playgroud)

有了这个实现:

@implementation Person

@synthesize name;

- (void)dealloc {
    [name release];
    [super dealloc];
}

- (void)sayHi {
    NSLog(@"Hello");
    NSLog(@"My name is %@.", name);
}

@end
Run Code Online (Sandbox Code Playgroud)

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

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 …
Run Code Online (Sandbox Code Playgroud)

iphone initialization objective-c null-pointer

35
推荐指数
3
解决办法
2万
查看次数