Where do you declare a constant in objective c?
我在一个头文件
1 2 3 4 5 6 7 8 | Ld /Users/Teguh/Library/Developer/Xcode/DerivedData/BadgerNew-bjopcgcgsjkcvcevflfbvsjwfgnu/Build/Products/Debug-iphonesimulator/BadgerNew.app/BadgerNew normal i386 cd /Users/Teguh/Dropbox/badgers/BadgerNew setenv MACOSX_DEPLOYMENT_TARGET 10.6 setenv PATH"/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin" /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-g++-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk -L/Users/Teguh/Library/Developer/Xcode/DerivedData/BadgerNew-bjopcgcgsjkcvcevflfbvsjwfgnu/Build/Products/Debug-iphonesimulator -F/Users/Teguh/Library/Developer/Xcode/DerivedData/BadgerNew-bjopcgcgsjkcvcevflfbvsjwfgnu/Build/Products/Debug-iphonesimulator -filelist /Users/Teguh/Library/Developer/Xcode/DerivedData/BadgerNew-bjopcgcgsjkcvcevflfbvsjwfgnu/Build/Intermediates/BadgerNew.build/Debug-iphonesimulator/BadgerNew.build/Objects-normal/i386/BadgerNew.LinkFileList -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -framework CoreLocation -framework UIKit -framework Foundation -framework CoreGraphics -framework CoreData -o /Users/Teguh/Library/Developer/Xcode/DerivedData/BadgerNew-bjopcgcgsjkcvcevflfbvsjwfgnu/Build/Products/Debug-iphonesimulator/BadgerNew.app/BadgerNew ld: duplicate symbol _EARTH_RADIUS in /Users/Teguh/Library/Developer/Xcode/DerivedData/BadgerNew-bjopcgcgsjkcvcevflfbvsjwfgnu/Build/Intermediates/BadgerNew.build/Debug-iphonesimulator/BadgerNew.build/Objects-normal/i386/NearbyIsiKota.o and /Users/Teguh/Library/Developer/Xcode/DerivedData/BadgerNew-bjopcgcgsjkcvcevflfbvsjwfgnu/Build/Intermediates/BadgerNew.build/Debug-iphonesimulator/BadgerNew.build/Objects-normal/i386/FrontPageofBadger.o for architecture i386 collect2: ld returned 1 exit status |
基本上,我希望常量可以用于我项目中的所有类。我应该在哪里申报?
您可以在头中声明,并在代码文件中定义它。只需声明为
1 | extern const double EARTH_RADIUS; |
然后在某个.m文件中(通常是在.m文件中声明的.h文件)
1 | const double EARTH_RADIUS = 6353; |
号
实现这一点有两种方法:
第一个选项-如以前的答复所指,.h文件中:
1 2 | myfile.h extern const int MY_CONSTANT_VARIABLE; |
在myfile.m中定义它们
1 2 | myfile.m const int MY_CONSTANT_VARIABLE = 5; |
。
第二种选择-我的最爱:
1 2 | myfile.h static const int MY_CONSTANT_VARIABLE = 5 ; |
在源文件中声明它,并具有与它的外部链接(使用extern关键字),以便在所有其他源文件中使用。
最好的做法是在.h和.m文件中声明它。关于同一个问题的一组非常详细的答案,请参阅目标C中的常数。