8
@interface Connections()
{
   static Connections *this;
}
@end

.m 文件中的上述代码引发编译器错误

类型名称不允许指定存储类

同时当

静止的

关键字被删除它运作良好 - 这很明显。目的:我想要静态和私有的“连接”实例。

为什么会出现这种行为,请帮忙。

4

1 回答 1

18

不能在 Objective-C 类中声明类级变量;相反,您需要将它们“隐藏”在实现文件中,通常给它们static-scope 以便它们不能被外部访问。

连接.m:

#import "Connections.h"

static Connections *_sharedInstance = nil;

@implementation Connections

...

@end

如果这是一个单例,您通常会定义一个类级别的访问器来在第一次使用时创建单例:

+ (Connections *)sharedInstance
{
    if (_sharedInstance == nil)
    {
        _sharedInstance = [[Connections alloc] init];
    }
    return _sharedInstance;
}

(并且您需要在 .h 文件中添加声明):

+ (Connections *)sharedInstance;
于 2013-02-19T14:47:50.130 回答