如何在目标c中从静态方法调用非静态方法?

编程入门 行业动态 更新时间:2024-10-25 21:26:05
本文介绍了如何在目标c中从静态方法调用非静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

推荐答案

[sharedInstance getPref]

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

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.

在一个类方法self中就是这个类本身。这就是你在该行上出错的原因,因为self不是该上下文中的实例。

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.

更多推荐

如何在目标c中从静态方法调用非静态方法?

本文发布于:2023-06-11 23:32:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/645318.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   方法   目标   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!