谁能告诉我,我在哪里出错了 . 我创建了一个名为BeaconData的NSobject . 头文件是:
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import <CoreBluetooth/CoreBluetooth.h>
@interface BeaconData : NSObject
@property (nonatomic, strong) NSMutableArray * jsonArray;
@property (nonatomic, retain) NSString * bMajor;
@property (nonatomic, retain) NSString * bMinor;
@property (nonatomic, retain) NSString * bUUID;
-(void) getData;
@end
然后是实现文件:
#import "BeaconData.h"
#define getDataURL @"http://www.eventav.biz/websitebeacons/library/json/files/beacons.txt"
@implementation BeaconData
@synthesize jsonArray, bUUID, bMajor, bMinor;
//Retrieve data
-(void) getData
{
extern NSString * bUUID;
extern NSString * bMajor;
extern NSString * bMinor;
NSURL * url = [NSURL URLWithString:getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//Loop through Json Array
for (int i = 0; i < jsonArray.count; i++)
{
bUUID = [[jsonArray objectAtIndex:i] objectForKey:@"i_uuid"];
bMajor = [[jsonArray objectAtIndex:i] objectForKey:@"i_major"];
bMinor = [[jsonArray objectAtIndex:i] objectForKey:@"i_minor"];
}
}
@end
接下来我尝试在主viewController.m文件中调用全局变量bMajor并将其打印出来 - 只是为了查看它是否有效,如下所示:
- (void)viewDidLoad {
[super viewDidLoad];
extern NSString * bMajor;
NSInteger beaconMajorInt = [bMajor integerValue];
NSLog (@"Beacon bMajor is %li", (long)beaconMajorInt);
但我得到的是以下错误:
架构x86_64的未定义符号:“_ bMajor”,引自: - ViewController.o中的[ViewController viewDidLoad] ld:找不到架构x86_64 clang的符号:错误:链接器命令失败,退出代码为1(使用-v查看调用)
1 回答
您已将
bMajor
变量声明为类属性 . 这意味着您必须实例化BeaconData
类的实例才能访问该变量,除非您包含类方法 .但是,在您的代码中,我发现您还希望将这些变量设置为全局变量 . 将变量声明为类属性然后尝试使其成为全局变量是多余的 . 在objective-c中,简单地在实现部分之外声明一个变量将使所有使用声明导入文件的模块都是全局的 . 你这样做:
您错误地使用了
extern
关键字 . 它应该在.h类文件中使用,以便让导入它的任何内容都知道它们可以访问此变量 . You also must declare it like I showed in the .m class file.h看起来像这样:
仅仅因为你能做到这一点并不意味着你应该这样做 . 根据您的代码,我怀疑您要做的是将
-getData
实例方法转换为单个类的类方法,允许类管理这些变量,同时保持良好的编码实践 .This SO Q/A should provide you exactly what you need to create your singleton.我建议你这样做 .
然后在viewController中,您可以通过使用类方法获取类的实例来访问这些变量 .