2

我知道在 Objective-C 中以及在 iOS SDK 上编程期间,一直使用指针。

在 Objective-C 中了解指针是否已初始化的最佳方法是什么?检查它是否为零?

CSomeClass *p;
//....
if(p==nil)
??

PS:换句话说,Objective-C 中变量的默认值是什么?指针?


更新

其实我有以下情况。

想象一下,我有一些指针Pointer *p1Pointer *p2在某个班级。然后想象有人调用这个类,即它是一个视图,必须显示。然后在我的课堂上我想检查是否没有初始化p1并且p2(例如,p1 == nil??p2==nil)我想显示空文本。

这些是在 Objective-C 中进行的某种比较吗?例如,如果没有初始化,默认值是p1多少p2?默认情况下,值是否被初始化为 Objective-C 中的某些内容?也许为空?

4

2 回答 2

3

在Objective C中了解指针是否已初始化的最佳方法是什么?检查它是否为零???

  • 是的,您是正确的(通过初始化,我假设您的意思是分配而不是设置默认属性的实际初始化)。您可以检查nil您是否已CSomeClass *p;在 ARC 中声明它。在非 ARC 中,您应该将其初始化为CSomeClass *p = nil;.

所以在这里你可以这样做,

if (p) { //or if (p != nil)
  //do your operations
} else { //same as if (!p) or if (p == nil)
  //display error message
}

Actually I have following situation. Imagine I have some pointers Pointer *p1, Pointer *p2 in some class. Then imagine someone calls this class, i.e., it is a view and must be displayed. Then in my class I want to check that if none had initialized p1 and p2 (e.g., p1 == nil? p2==nil?) I want to display empty text. Are these sort of comparisons done in ObjC?

  • Yes, that is fine in Objective C. You can check it as if (p1 && p2) or if ((p1 != nil) && (p2 != nil)). Both are fine. In the else part, you can add the empty text which should be displayed.

For example what are the default values of p1 and p2 if they were not initialized? Do values by default get initialized to something in ObjC?? maybe to null?

  • In ARC, it will be nil. In non-ARC you should equate to CSomeClass *p1 = nil; before doing this or else it will be a dangling pointer with some garbage value.

Here is the documentation on ARC.

于 2012-12-25T07:54:18.427 回答
1

Something important to understand here is that Objective-C uses reference counting - this is why the terminology of saying "a pointer is initialized" is a bit problematic.

The way to know if an object even exists (Doesn't mean it's initialized!)

if (!object) {
      NSLog(@"Object is nil");
}

If you wish to release an object, it's always best practice to nil it out. This way, others won't send a message to deallocated instance (causes a nasty crash):

[object release],object = nil;
于 2012-12-25T07:55:16.627 回答