How to call non static method from static method i

2019-09-17 07:37发布

问题:

I am having a class in which i am using singleton pattern.I have static method.Now i want call a non static method inside the static method.But i am not able to call it.Please tell me what is the solution.

#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

回答1:

[sharedInstance getPref]

non static methods are instance methods. the receiver must be an instance. in your case, the instance you want to use is of course the sharedInstance that you just created.

inside a class method self is the class herself. that's why you get an error on that line, because self is not an instance in that context.