How to access self in class method objective C

拥有回忆 提交于 2019-12-12 16:55:21

问题


I havea Utility class that uses class methods. I am trying to refer to self in the class method but can't. I was wondering how would I declare the following in a class method:

[MRProgressOverlayView showOverlayAddedTo:self.window animated:YES];

self.window it says member reference type struct objc_class *' is a pointer; maybe you meant to use '->'

Another problem that relates to not being able to call self is how would I refer to a declared @property in my .h in a class method in my .m.

Here is my class method:

.m
+ (void)showHUD
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
    [MRProgressOverlayView showOverlayAddedTo:self.window animated:YES];

    //I would preferably like to call my property here instead
}


.h
@property (nonatomic) MRProgress * mrProgress;

回答1:


The whole point of a class method is that it is not part of a specific instance. Inside of a class method, self is the class.

If you need to be tied to a specific instance, then it should be an instance method. If you want a static method that accesses a specific instance, then pass that instance (self) to it (though it's hard to imagine many cases where that makes sense).

In the above example, showHUD should be an instance method almost certainly. If that doesn't make sense for some reason, then it should be:

+ (void)showHUDForWindow:(UIWindow *)window;

You can then call it as showHUDForWindow:self.window and use that as needed.




回答2:


You can use a singleton pattern. Singleton pattern assumes that the only instance of your class exists. Since it's the only instance, you can then use it from class methods.

Example implementation:

+ (MyClass*)sharedInstance {
    static dispatch_once_t once;
    static MyClass *sharedMyClass;
    dispatch_once(&once, ^ {
        sharedMyClass = [[self alloc] init];
    });
    return sharedMyClass;
}

Then you can access the shared instance via [MyClass sharedInstance], for example:

+ (void)doSomethingCool {
   [[self sharedMyClass] doSomething];
}


来源:https://stackoverflow.com/questions/27255506/how-to-access-self-in-class-method-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!