我之前从未在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)
答案 0 :(得分:6)
在您的实现中,name
不是实例变量,而是全局变量。将声明放在@implementation
块中的事实并不会使它成为实例变量。
如果您想让name
成为实例变量,请将其声明为类扩展的一部分,如下所示:
@interface ViewController2 () {
NSString *name;
}
@end
请注意,如果您需要name
为static
,那么您的方法就会奏效,因为static
变量会从班轮中“隐藏”。