【问题标题】:Access Class without initializing无需初始化的访问类
【发布时间】:2012-10-17 10:27:24
【问题描述】:

我想用它的方法在 Objective-c 中创建一个类,以便访问数据时我不想实例化该类。我该怎么做?

【问题讨论】:

  • 如何从另一个类调用它?

标签: objective-c ios


【解决方案1】:

您可以使用singleton,或者如果您打算只使用静态方法,您可以将其添加到类中并直接与类名一起使用。

将方法创建为静态,

+(void)method;

然后将其用作,

[MyClass method];

仅当您创建一些实用程序类时才有用,这些实用程序类只有一些实用程序方法,例如处理图像等。如果你需要有属性变量,你需要singleton

例如:-

转到新文件并创建 MySingleton 类,该类将创建 MySingleton.hMySingleton.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 等情况。

【讨论】:

  • 我怎样才能从这种实现中访问文本视图?
  • 我也用这个问题的答案更新了我的答案。另外,为什么要像这样使用 textview 而不是创建为局部变量?有什么特别的原因吗?
【解决方案2】:

你可以使用单例模式,检查这个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";    

【讨论】:

  • 我已经编写并分配了我的类,但我只能在分配它的地方使用它......有没有办法使用它和全局变量就像我在.h中写的一样
  • 无论如何你需要以某种方式存储指向它的指针。也许您可以向您的 AppDelegate 添加一个属性或创建一个单例类(如我的回答)并在其中添加该指针。
猜你喜欢
  • 2022-01-20
  • 1970-01-01
  • 2020-08-25
  • 2020-09-08
  • 2021-09-29
  • 2019-10-12
  • 2020-11-30
  • 2021-11-02
  • 2022-01-04
相关资源
最近更新 更多