0

我有类似的东西

#define IS_IPHONE_5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"https://www.test.com/"]];

KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"xyz" accessGroup:nil];

我必须一直在我的所有文件中定义。有没有办法可以在一个文件中定义它们,每次都导入它?

编辑

所以按照建议我将它添加到我的应用程序委托中

#import <UIKit/UIKit.h>
@class AFHTTPClient;
@class KeychainItemWrapper;

@interface TestAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, strong, readonly) AFHTTPClient *httpClient;
@property (nonatomic, strong, readonly) KeychainItemWrapper *keychainItem;
@end

然后尝试在我的视图控制器中将我的 httpClient 定义为

httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"https://www.test.com/"]];

它给了我一个错误说use of undeclared identifier 'httpClient'

4

4 回答 4

0

是的,您创建一个带有声明常量的文件并每次都导入它:)

于 2013-03-09T09:12:31.850 回答
0

有很多方法。您可以创建一个专用的头文件。您可以将类别放在AFHTTPClient和上KeychainItemWrapper

我可能会将所有这些都放入我的AppDelegate. 您不必导入AFHTTPClient.hKeychainItemWrapper.h执行AppDelegate.h此操作。您可以只前向声明类:

@class AFHTTPClient;
@class KeychainItemWrapper;

@interface AppDelegate : NSObject <UIApplicationDelegate>

@property (nonatomic, readonly) BOOL isIPhone5;
@property (nonatomic, strong, readonly) AFHTTPClient *httpClient;
@property (nonatomic, strong, readonly) KeychainItemWrapper *keychainItem;

...

然后,您只需在实际需要使用这些对象的文件中包含AFHTTPClient.h和。KeychainItemWrapper.h

顺便说一句,比较DBL_EPSILON是没有意义的。首先,在 iOS 上,CGFloat是 的别名float,而不是double. 您不必要地转换为double. 其次,height屏幕的 568。单精度float可以精确表示 -16777216 和 16777216 之间的每个整数,包括 568。您可以只测试是否相等。

于 2013-03-09T09:19:43.853 回答
0

我已经好几年没有制作一个全局常量文件了……总有一个更好、更本地化的地方来存放这样的定义。尽管如此,这样的功能还是有用的——会回答,但请考虑如何将它们声明为更接近需要它们的实现。

  • 创建头文件和源文件
  • 要么声明 C 函数,要么声明具有类方法的 ObjC 类接口。
  • 定义函数/方法
  • 然后#import仅在需要时使用“全局常量”标头(不在 PCH 中)

使用 C 函数的示例:

// MONApp_Constants.h
// no #imports up here

extern bool MONApp_Is_iPhone5(void);

@class AFHTTPClient;
extern AFHTTPClient * MONApp_HTTPClient(void);

@class KeychainItemWrapper;
extern KeychainItemWrapper * MONApp_KeychainItem(void);

当然,如果您只需要一个实例,您将需要找到一个保存对象引用的好地方。在这种情况下,函数不应该是全局可见的。

于 2013-03-09T11:14:01.747 回答
0

您需要在名为 constants.h 的文件中声明全局变量,并在必要时导入其他文件。

我建议你不要这样做:

#define httpClient [[[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"https://www.test.com/"]]];

您尝试请求的 URL 的原因可能会有所不同。#define 的想法是拥有不变的项目。即使您总是向@“ https://www.test.com/ ”请求,我仍然不建议您这样做。

希望这可以帮助...

于 2013-03-09T16:17:15.253 回答