【发布时间】:2012-10-17 10:27:24
【问题描述】:
我想用它的方法在 Objective-c 中创建一个类,以便访问数据时我不想实例化该类。我该怎么做?
【问题讨论】:
-
如何从另一个类调用它?
标签: objective-c ios
我想用它的方法在 Objective-c 中创建一个类,以便访问数据时我不想实例化该类。我该怎么做?
【问题讨论】:
标签: objective-c ios
您可以使用singleton,或者如果您打算只使用静态方法,您可以将其添加到类中并直接与类名一起使用。
将方法创建为静态,
+(void)method;
然后将其用作,
[MyClass method];
仅当您创建一些实用程序类时才有用,这些实用程序类只有一些实用程序方法,例如处理图像等。如果你需要有属性变量,你需要singleton。
例如:-
转到新文件并创建 MySingleton 类,该类将创建 MySingleton.h 和 MySingleton.m 文件。
在.h文件中,
@interface MySingleton : NSObject
{
UIViewController *myview;
}
@property (nonatomic, retain) UIViewController *myview;
+(MySingleton *)sharedSingleton;
在.m文件中,
+ (MySingleton*)sharedSingleton {
static MySingleton* _one = nil;
@synchronized( self ) {
if( _one == nil ) {
_one = [[ MySingleton alloc ] init ];
}
}
return _one;
}
- (UIViewController *)myview {
if (!myview) {
self.myview = [[[UIViewController alloc] init] autorelease]; //you can skip this, but in that case you need to allocate and initialize the first time you are using this.
}
return myview;
}
然后将其用作,
[[MySingleton sharedSingleton] myview] 项目中的任何位置。不过记得导入MySingleton.h。同样,您可以在单例中创建任何对象并使用它。只需相应地实现 getter 或 setter 方法即可。
你必须小心的一件事是,在单例中创建的对象只分配了一个内存空间,因此无论何时在项目中的任何地方使用它都是同一个对象。上面的代码不会在类中创建myview 对象的多个副本。因此,每当您修改 myview 的属性时,该属性将随处反映。仅当绝对需要并且您需要从整个项目中访问单个对象时才使用此方法。通常,我们仅将其用于存储需要从不同类访问的 sessionID 等情况。
【讨论】:
你可以使用单例模式,检查这个question。
像这样:
+(MySingleton *)sharedInstance {
static dispatch_once_t pred;
static MySingleton *shared = nil;
dispatch_once(&pred, ^{
shared = [[MySingleton alloc] init];
shared.someIvar = @"blah";
});
return shared;
}
或者如果你只想访问方法,你可以使用工厂方法(那些带+的,而不是带-的)
@interface MyClass
@property (nonatomic, assign) NSInteger value;
+ (void) factoryMethod;
- (void) instanceMethod;
...
// then in code
[MyClass factoryMethod]; // ok
[[MyClass sharedInstance] instanceMethod]; // ok
[MyClass sharedInstance].value = 5; // ok
更新:
您可以将属性添加到appDelegate
// in your app delegate.h
@property (nonatomic, retain) UIViewController* view;
// in your app delegate.m
@synthesize view;
并从几乎任何地方获取appDelegate,例如:
myapp_AppDelegate* appDelegate = [[UIApplication sharedApplicaton] delegate];
appDelegate.view = ...; // set that property and use it anywhere like this
请注意,您需要 #import 您的 UIViewController 子类和您的 appDelegate.h 才能使自动完成工作并且有时避免警告。
// someFile.m
#import "appDelegate.h"
#import "myViewController.h"
...
myapp_AppDelegate* appDelegate = [[UIApplication sharedApplicaton] delegate];
appDelegate.view.myLabel.text = @"label text";
【讨论】: