use*_*004 1 iphone xcode objective-c
我想知道在调用函数之前,目标C是否进行任何检查以查看指向对象的指针是否为nil.
例如,说我有一个
myObject* ptr;
Run Code Online (Sandbox Code Playgroud)
并初始化
ptr = nil;
Run Code Online (Sandbox Code Playgroud)
并打电话
[self myFunction:ptr];
Run Code Online (Sandbox Code Playgroud)
其中myFunction是我自己的函数,并且不检查对象是否为nil.我听说某个目标C不会调用该函数,如果它是零的话?这是真的,我的代码会安全吗?
我问的原因是因为我正在实现一个通用应用程序,并且有一个只适用于ipad的UIView实例.但是,我为这个视图做了很多函数调用,而不是在调用函数之前进行条件检查以查看它是否是ipad,如果我将视图设置为nil,如果它是iphone,那将是很好的.
此外,如果接口构建器分配了对象并且我将指针设置为nil,是否会出现内存泄漏或构建器是否知道解除对象的释放?
谢谢
你总是可以提供一个带nil参数的方法,但我认为你可能误解的是关于消息传递nil.
MyClass *object = nil;
[object doSomething]; // nothing done, because object is nil
object = [[MyClass alloc] init];
[object doSomething]; // does something, because object points to an instance
Run Code Online (Sandbox Code Playgroud)
为了证明提供nil作为一个论点:
NSMutableDictionary *myDict = [NSMutableDictionary dictionary];
[myDict setObject:@"Value 1" forKey:@"Key 1"];
[myDict setObject:nil forKey:@"Key 1"]; // perfectly valid
// myDict is empty again after setting nil value for "Key 1".
myDict = nil;
[myDict setObject:@"Value 1" forKey:@"Key 1"]; // nothing happens!
Run Code Online (Sandbox Code Playgroud)
在上述情况下,object和myDict被称为"接收器".当接收器是时nil,不执行任何动作.这与其他编程语言完全不同,例如,在C++中,以下内容无效:
MyClass *object = NULL;
object->doSomething(); // oops, this is not allowed
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
237 次 |
| 最近记录: |