-1

我在objective-c中遇到了一些单例问题。虽然我没有在 Objective-c 中看到过这样的例子,但我决定使用单例来促进 ViewController 之间的通信。据我了解,这不是鼓励在视图控制器之间进行通信的方式,但我想我会试一试。

所以,对于我的单身人士,我有:

+(FirstViewController*) getInstance;

在头文件中定义。这将允许外部呼叫者访问它。实现如下:

 static FirstViewController* _instance;
 +(FirstViewController*) getInstance
 {
      //I assume there will be only one copy of this throughout the project, so        
      //pointer confusion is not an issue here, hens it being a singleton
      if (_instance == nil)
      {
           _instance = (FirstViewController*)self;
      }

      return _instance;
 }

这可能会引起麻烦的第一个提示是 XCode 抱怨我将实例指针设置为 self. 警告是:

 Incompatible pointer types assigning to "FirstViewController*" from 'class'

好的,警告指出,看起来我正在尝试将一个指针应用于另一个指针。将其转换为 FirstViewController 会使警告消失(因为它现在是正确的指针类型),但记住这可能是未来可能问题的根源并没有什么坏处。

在 FirstViewController 我有一个功能

-(void)assignWord:(NSString *)w

我应该能够通过单例实例来解决这个问题。在我的第二个视图控制器中,我通过以下方式调用它:

FirstViewController* controller = [FirstViewController getInstance];
[controller assignWord:string];

但是,这最终会崩溃。更加具体:

+[FirstViewController assignWord:]: unrecognized selector sent to class

对此非常奇怪的一件事是它试图将其作为静态函数调用,而不是在实例内部。

在调试过程中逐步执行此操作时我注意到的另一件事是,当我将断点设置为单例的返回时,_instance 变量仍然为零

 self   Class   FirstViewController 0x0000000100006b98
_instance   SecondViewController *  nil 0x0000000000000000

有点奇怪的是 _instance 被视为 SecondViewController;我的猜测是它与调用者有关。

我不经常做objective-c。有没有其他人遇到过这个?知道我为什么会出现奇怪的行为吗?(调试器是否足够可靠?)

注意:被传递的字符串指针是一个有效的 NSString

4

2 回答 2

1

You should be initializing _instance in your if (_instance == nil). After all, if _instance is nil, then it doesn't exist and you need to make it exist by actually allocating memory. Your statement _instance = (FirstViewController*)self; doesn't do any of this.

Secondly, this is a class method, not an instance method, therefore self doesn't have the meaning you probably expect: it is not an instance of anything (and therefore cannot refer to a singleton instance).

于 2013-09-29T08:39:23.010 回答
0

Change your _instance = (FirstViewController*)self; to

_instance = [[FirstViewController alloc] init]
于 2013-09-29T09:37:33.060 回答