objective-c - Xcode:为什么我不能在一个项目中有重复的 ivars?出现重复符号错误

标签 objective-c xcode

我以前从未在 Xcode 中注意到这一点,但是当我尝试重用同名 ivar 时出现此错误。我用 2 个 ViewController 创建了一个简单的项目,它们都有 ivar 名称。

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

NSString *name;

- (void)viewDidLoad {
    [super viewDidLoad];

    name = @"me";

    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

#import "ViewController2.h"

@interface ViewController2 ()

@end

@implementation ViewController2

NSString *name;

- (void)viewDidLoad {
    [super viewDidLoad];

    name = @"Me";

    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

当我运行这个项目时,我得到了这个错误:

duplicate symbol _name in:
    /Users/cta/Library/Developer/Xcode/DerivedData/testDuplicate2-cxeetzeptbwtewfecgmoonzgzeyl/Build/Intermediates/testDuplicate2.build/Debug-iphoneos/testDuplicate2.build/Objects-normal/arm64/ViewController.o
    /Users/cta/Library/Developer/Xcode/DerivedData/testDuplicate2-cxeetzeptbwtewfecgmoonzgzeyl/Build/Intermediates/testDuplicate2.build/Debug-iphoneos/testDuplicate2.build/Objects-normal/arm64/ViewController2.o
ld: 1 duplicate symbol for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

最佳答案

在你的实现中 name 不是一个实例变量,它是一个全局变量。事实上,您将它的声明放在 @implementation block 中并不能使它成为一个实例变量。

如果你想使 name 成为一个实例变量,将其声明为你的类扩展的一部分,如下所示:

@interface ViewController2 () {
    NSString *name;
}
@end

请注意,如果您需要 namestatic,您的方法会奏效,因为 static 变量在衬里中是“隐藏”的.

关于objective-c - Xcode:为什么我不能在一个项目中有重复的 ivars?出现重复符号错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31665858/

相关文章:

iphone - 收到内存警告。等级=1

objective-c - 使用 dateFromComponents 时,将 NSDateComponents 中的日期设置为大于 31 的日期?

iphone - 分配给 'ViewController' 的指针类型不兼容

objective-c - 在核心数据中设置一个自动递增的字段

iphone - iOS 6 - (BOOL)shouldAutorotate 不被调用导航 Controller 推送 viewControllers

ios - 强烈提及委托(delegate)

iphone - ios:改变方向后UIView的宽高不准确?

xcode - 如何从 Swift 失败结果的自定义错误枚举中获取原因

ios - Xcode 上传二进制 Apple 的 Web 服务操作不成功

ios - 在iOS 13和iOS 11.4中从字符串转换日期的不同结果