ios - 如何从 objective-c 中的静态方法调用非静态方法?

标签 ios objective-c iphone ipad oop

我有一个使用单例模式的类。我有静态方法。现在我想在静态方法中调用一个非静态方法。但我无法调用它。请告诉我解决方案是什么.

#import "ThemeManager.h"

@implementation ThemeManager

+(ThemeManager *)sharedInstance
{
    NSLog(@"shared instance called");
    static ThemeManager *sharedInstance = nil;

    if (sharedInstance == nil)
    {
        sharedInstance = [[ThemeManager alloc] init];
    }
    [self getPref];//i get error at this line
    return sharedInstance;
}
-(void)getPref
{
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *themeName = [defaults objectForKey:@"theme"] ?: @"default";
        NSLog(@"theme name is %@",themeName);
        NSString *path = [[NSBundle mainBundle] pathForResource:themeName ofType:@"plist"];
        self.theme = [NSDictionary dictionaryWithContentsOfFile:path];



}
@end

最佳答案

[sharedInstance getPref]

非静态方法是实例方法。接收者必须是一个实例。在您的情况下,您要使用的实例当然是您刚刚创建的 sharedInstance。

在类方法中,self 是类本身。这就是为什么你在该行收到错误的原因,因为 self 不是该上下文中的实例。

关于ios - 如何从 objective-c 中的静态方法调用非静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31426411/

相关文章:

ios - 如果部署了有效证书,iOS AFNetwork SSL Pinning 模式是否会提供额外的安全奖励

ios - 预填充的 Realm 不会在第一次启动时被复制

objective-c - Uncrustify:函数名称和行尾大括号之间有空格

iphone - CallStateDisconnected 仅检测到来电,而不检测从我的应用发出的调用

ios - 在 swift 5 中使用 UITabBar.appearance().bar 样式崩溃

javascript - 添加到主屏幕后 iPhone WebApp 无法正常工作

objective-c - 在appDelegate init方法中启动self.window

ios - nativescript 如何使元素对触摸事件透明

ios - 在后台模式下未调用 didReceiveRemoteNotification

iphone - Facebook 与 Phonegap iOS 连接