如何在课堂上访问自我的方法目标C
我有一个使用类方法的工具类。 我正在尝试在类方法中引用自我,但不能。 我想知道如何在类方法中声明以下内容:
[MRProgressOverlayView showOverlayAddedTo:self.window animated:YES];
self.window
它说成员引用typesstruct objc_class *' is a pointer; maybe you meant to use '->'
struct objc_class *' is a pointer; maybe you meant to use '->'
另一个涉及不能self
调用的问题是如何在我的.m
中的类方法中引用我的.h
中声明的@property
。
这是我的class级方法:
.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;
类方法的重点在于它不是特定实例的一部分。 在类方法中, self
是类。
如果你需要绑定到一个特定的实例,那么它应该是一个实例方法。 如果你想要一个访问特定实例的静态方法,然后将该实例( self
)传递给它(尽pipe很难想象许多情况下有意义)。
在上面的例子中, showHUD
几乎可以肯定是一个实例方法。 如果由于某种原因没有意义,那么应该是:
+ (void)showHUDForWindow:(UIWindow *)window;
然后你可以调用它作为showHUDForWindow:self.window
并根据需要使用它。
你可以使用单例模式。 单例模式假定你的类的唯一实例存在。 由于它是唯一的实例,所以可以使用它从类方法。
示例实现:
+ (MyClass*)sharedInstance { static dispatch_once_t once; static MyClass *sharedMyClass; dispatch_once(&once, ^ { sharedMyClass = [[self alloc] init]; }); return sharedMyClass; }
然后您可以通过[MyClass sharedInstance]
访问共享实例,例如:
+ (void)doSomethingCool { [[self sharedMyClass] doSomething]; }