Flo*_*rin 35 iphone initialization objective-c null-pointer
为了使我所说的更清楚,这是一个例子.
有这个课程:
@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 here
Run Code Online (Sandbox Code Playgroud)
Rob*_*ger 63
发送到nil
对象的消息在Objective-C中是完全可以接受的,它被视为无操作.没有办法将它标记为错误,因为它不是错误,实际上它可能是该语言的一个非常有用的功能.
来自文档:
发送消息为零
在Objective-C中,将消息发送到nil是有效的 - 它在运行时根本没有效果.Cocoa中有几种模式可以利用这一事实.从消息返回到nil的值也可能是有效的:
如果该方法返回一个对象,则发送一条消息给
nil
returns0
(nil
),例如:
Person *motherInLaw = [[aPerson spouse] mother];
如果
aPerson
的spouse
是nil
,随后mother
被送到nil
并且该方法返回nil
.如果该方法返回任何指针类型,任何大小小于或等于
sizeof(void*)
afloat
,adouble
,along double
或a的整数标量long long
,则发送给nil
返回的消息0
.如果该方法返回a
struct
,如Mac OS X ABI函数调用指南所定义的那样在寄存器中返回,那么发送的消息将nil
返回0.0
数据结构中的每个字段.其他struct
数据类型不会用零填充.如果该方法返回除上述值类型之外的任何内容,则发送到nil的消息的返回值是未定义的.
Hea*_*ers 13
来自Greg Parker的网站:
如果运行LLVM Compiler 3.0(Xcode 4.2)或更高版本
Messages to nil with return type | return Integers up to 64 bits | 0 Floating-point up to long double | 0.0 Pointers | nil Structs | {0} Any _Complex type | {0, 0}
您应该清楚的一点是,在Objective-C中,您不会在对象上调用方法,而是向对象发送消息.运行时将找到该方法并调用它.
从Objective-C的第一个版本开始,给nil的消息一直是一个安全的无操作,返回nil.有很多代码依赖于这种行为.
归档时间: |
|
查看次数: |
19593 次 |
最近记录: |