Xcode:为什么我不能在项目中复制ivars?得到重复的符号错误

son*_*nce 2 xcode objective-c

我以前从未在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
Run Code Online (Sandbox Code Playgroud)

当我运行该项目时,我收到此错误:

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)
Run Code Online (Sandbox Code Playgroud)

das*_*ght 6

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

如果要创建name实例变量,请将其声明为类扩展的一部分,如下所示:

@interface ViewController2 () {
    NSString *name;
}
@end
Run Code Online (Sandbox Code Playgroud)

请注意,如果你需要的namestatic,你的做法会工作,因为static变量是自内衬"隐藏".