【问题标题】:No Visible @ interface fro 'NSObject', declares the selector 'alloc''NSObject' 没有可见的@接口,声明选择器'alloc'
【发布时间】:2014-04-23 02:19:33
【问题描述】:

我正在尝试创建一个单例。这组代码旨在建立一个 settingsMAnager 单例。

我正在尝试分配它,但一直抛出错误

它抛出错误 no visible @ interface with NSObject。 声明选择器'alloc'

有人能看出什么问题吗?

提前致谢!

//In my .h file I have

    +(settingsManager*)getInstance;
    -(void)printSettings;


//In My .m file is----

    static settingsManager *theInstance = nil;

//Instance Method
    +(settingsManager*)getInstance
    {


         (theInstance == nil)

        {
            [[self alloc] init];//Im getting "expression result unused" here
        }

    return theInstance;

    }

    -(id)alloc

    {
        theInstance = [super alloc];<------//getting the big error here 


    return theInstance;

    }

    -(id)init
    {

    if (self = [super init])

         {

    }
    return  self;


}
(void)printSettings                                                                                                                                                                                   


{



    NSLog(@"Hello");




}

【问题讨论】:

    标签: objective-c


    【解决方案1】:

    这不是right way to implement a singleton。在您的实现中存在许多单一且具有潜在风险的位。然而,这个错误是因为alloc 是一个类方法,而不是你在这里写的实例方法。

    【讨论】:

    • 我要感谢大家的帮助....我不敢说我​​是新人...我一生都想成为一名计算机人。我终于开始学习了,很高兴找到一个知识渊博的人社区来寻找方向。我会更加注意网站的指导方针,比如标记某人的回答有帮助..我很抱歉..我一年半只发了四篇帖子所以..谢谢大家的帮助!
    【解决方案2】:

    你不应该继承alloc 方法。下面是使用单例的代码:

    + (instancetype)sharedInstance {
        
        static SettingsManager *sharedInstance = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            sharedInstance = [[settingsManager alloc] init];
        });
        return sharedInstance;
    }
    

    如果你有兴趣阅读更多内容,我建议你this link

    我还建议您阅读推荐的 coding guidelines 用于 Objective-c。



    实例类型

    instancetype 是一个上下文关键字,可用作结果类型来表示方法返回相关的结果类型。 instancetype 与 id 不同,只能用作方法声明中的结果类型。更多详情here.

    dispatch_once

    正如here 解释的那样,dispatch_once() 是同步的,只允许您执行一段代码一次。

    【讨论】:

    • 谢谢 jbouaziz....感谢您的建议和内容丰富的阅读。我会看两个!
    • 很高兴听到这个消息!那你能接受答案吗?谢谢!
    • jbouaziz...你能具体解释一下第四行发生了什么吗?该代码有效....您是否正在创建令牌?我以后需要用这个吗?我将需要使用 instanceType 和 sharedInstance 并且我知道如何......只是不熟悉该语法。您能否为刚刚获得难题答案的人详细说明?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多