gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:43:30 25 4
gpt4 key购买 nike

当我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com