iphone - 静态变量使用不当?

标签 iphone objective-c ios static

A 类有一个 UIImage。

B 类具有对类型 A 的类的静态引用。

在B类实例化之前,我想调用B类中的一个静态方法来为A类实例赋值。

+ (void)setClassAReference:(ClassA*)classA
{
    classA_ = classA;
}

这可能吗?

在我深入研究我当前的项目之前,我创建了一个示例,并且能够设置一个整数值,然后用它实例化 B,保留存储的值并允许访问它。

但是,在我当前的项目中,XCode 拒绝让我传递整数值:

A类中的非静态方法:

- (UIImage*)imageWithIdentifier:(ImageIdentifier)identifier; // identifier is enum type

类B实例化后,我尝试调用类A中的一个方法:

UIImage *img = [classA_ imageWithIdentifier:ImageIdentifier_Foo];

但是我收到隐式转换警告。自动完成显示 (id) 而不是 (ImageIdentifier)。我已经对所有方法签名进行了三重检查,它们都使用了枚举类型。

我是不是错误地使用了静态变量,还是有其他问题?我知道我可以使用单例,但如果可能的话我不想这样做。

我在这里添加枚举声明:*

typedef enum
{
  ImageIdentifier_Foo = 0,
  ImageIdentifier_Bar
} ImageIdentifier;

*更改真实姓名以保护无辜者。

最佳答案

首先...

如果你想在类实例化之前初始化类的静态变量,你可以使用 NSObject 的类方法

+ (void) initialize

这是您可以在 ClassB 中分配静态 ClassA 变量的地方。

其次......

确保保留该 classA 变量,否则它将被释放。

第三......

关于您的隐式转换...变量“a”是什么,您在上面写了 classA_。你能展示你的枚举声明吗?你有导入ClassA吗?

我没有任何编译错误:

A类.h

typedef enum
{
    ImageIdentifier_Foo = 0,
    ImageIdentifier_Bar
} ImageIdentifier;

@interface ClassA : NSObject

- (UIImage*)imageWithIdentifier:(ImageIdentifier)identifier; // identifier is enum type

@end

A类.m

#import "ClassA.h"

@implementation ClassA

- (UIImage*)imageWithIdentifier:(ImageIdentifier)identifier {
    return nil;
}

@end

B类.h

@interface ClassB : NSObject

@end

B类.m

#import "ClassB.h"
#import "ClassA.h"

static ClassA *classA;

@implementation ClassB

+ (void) initialize {
    classA = [[ClassA alloc] init];
}

- (void) doSomething {
    UIImage *image = [classA imageWithIdentifier:ImageIdentifier_Foo];
    NSLog(@"image %@", image);
}

@end

关于iphone - 静态变量使用不当?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9243500/

相关文章:

ios - 尝试使用 AVFoundation 从前置摄像头捕获照片时出现 fatal error

ios - 在应用程序更新中发布新的 SQLite 数据库

ios - 如何找到 iphone 相机照片的大小以及如何调整它的大小?

iphone - ios 中的 Twitter 框架帐户配置?

objective-c - 摆脱多余的#import行

objective-c - iPad+将图像选择器质量设置为低

iPhone "count"挫折?

ios - 在未安装的机器上运行 Cocoa Pods 应用程序

iphone - 异步函数执行?

iphone - 如何将触摸从 UITextView 传递到 UITableViewCell