Xcode:为什么我的项目中没有重复的ivars?得到重复的符号错误

时间:2015-07-28 01:10:19

标签: objective-c xcode

我之前从未在Xcode中注意到这一点,但是当我尝试重用同名的ivar时,我收到了这个错误。我用2个ViewControllers创建了一个简单的项目,它们都有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)

1 个答案:

答案 0 :(得分:6)

在您的实现中,name不是实例变量,而是全局变量。将声明放在@implementation块中的事实并不会使它成为实例变量。

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

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

请注意,如果您需要namestatic,那么您的方法就会奏效,因为static变量会从班轮中“隐藏”。