ios - Objective-C 常量 : Xcode build failure for simulator while success in iPhone

标签 ios iphone objective-c xcode constants

当我在 Xcode 5 中为 iPhoneSimulator 构建这个 2 类简单 iOS 项目时,它报告“重复符号 _FLAG”或“ undefined symbol _TAG”,这取决于我是否在“构建阶段”中添加“Constant.m”=>编译源”或不。但奇怪的是,它为真正的 iPhone 成功构建(在编译源中添加 Constant.m 时)。有人能帮帮我吗?我真的需要在模拟器中调试我的项目(更快)。谢谢。

Constant.h
#import <Foundation/Foundation.h>
const int FLAG = 3;
extern NSString *const TAG;
@interface Constant : NSObject
@end

Constant.m
#import "Constant.h"
NSString *const TAG = @"hello";
@implementation Constant
@end

Deck.h
#import <Foundation/Foundation.h>
@interface Deck : NSObject
+ (void)sayHi;
@end

Deck.m
#import "Deck.h"
#import "Constant.h"
@implementation Deck
+ (void)sayHi
{
    NSLog(@"%@", TAG);
}
@end

更新:(@trojanfoe) 通过 Constant.h 中的 extern int 并在 Constant.m 中定义它们的值,修复了构建警告。但作为返回,许多代码如 switch (i) case CONSTANT 不起作用。它返回到 #define。任何其他方法将不胜感激。或者解释为什么为 iPhone 构建是好的而为模拟器构建不是?也许是模拟器的“绕过”?

[答案](来自@trojanfoe) 使用 enum 是解决问题的更好方法。 我的测试:

Constant.h
...
enum FlagType {FLAG_A = 0, FLAG_B = 1};
...

Deck.m
...
switch (i) {
  case FLAG_A:
  //do sth...
  break;
}

背景信息:我想为多个类包含一个常量 header 。它包含 int 和 NSString。虽然 #define 有效,但它不是使用常量的好方法。这就是为什么我要像上面那样尝试。

最佳答案

需要在头文件中将FLAG声明为extern,并在实现文件中定义(不需要声明/定义常量类):

常量.h

#import <Foundation/Foundation.h>
extern const int FLAG;
extern NSString *const TAG;
//@interface Constant : NSObject
//@end

常数.m

#import "Constant.h"
const int FLAG = 3;
NSString *const TAG = @"hello";
//@implementation Constant
//@end

但是你也可以使用预处理器常量:

#define FLAG 3

关于ios - Objective-C 常量 : Xcode build failure for simulator while success in iPhone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24241760/

相关文章:

ios - 如何在masterViewController中呈现modalViewController?

ios - 应用扩展名称不能与应用名称相同?

Objective-C 2.0 和快速枚举抛出异常

ios - App Like Ovoo 视频通话

iphone - 我何时以及为何需要释放对象?

ios - 为什么我的应用程序恢复后不返回到我的详细 View ?

ios - 带有 flexbox 的 Bootstrap 列在 iOS 和 Safari 上的宽度不正确

ios - UIWebView 在 [UIViewAnimationState 发布] : message sent to deallocated instance 随机崩溃

ios - 在 Swift SpriteKit 项目中播放声音?

iphone - UIDeviceOrientation 横向模式下未知