How to access an object of class self in class C

I have a Utility class that uses the methods of the class. I am trying to reference myself in a class method but cannot. I was wondering how to declare the following in a class method:

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

      

self.window

it refers to a member reference type struct objc_class *' is a pointer; maybe you meant to use '->'

Another problem with not being able to call self

is how I can refer to a declared @property

in mine .h

in a class method in mine .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;

      

+3


source to share


2 answers


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

is a class.

If you need to bind to a specific instance, then it must be an instance method. If you want a static method to access a specific instance, pass that instance ( self

) to it (although it's hard to imagine many cases where this makes sense).

The example above showHUD

should be an instance method almost certainly. If for some reason this doesn't make sense, then it should be:



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

      

Then you can call it showHUDForWindow:self.window

and use it as needed.

+9


source


A singleton pattern can be used. The Singleton pattern assumes that there is only one instance of your class. Since this is the only instance, you can use it from the class methods.

Implementation example:

+ (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];
}

      

0


source







All Articles