我的课程中有2节课 第一个类是class1,第二个类是class2.I想在类1中创建和初始化全局变量并在类2中使用但编译器给我这个错误XD:
Undefined symbols for architecture i386:
"_saeid", referenced from:
-[class2 viewDidLoad] in class2.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
我在class1中创建了全局变量,并以这种方式在class2中运行,但不起作用:
class1.h
extern int saeid; // this is global variable
@interface class1 : UITableViewController<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong) IBOutlet UITableView *table;
@end
class1.m
#import "class1.h"
#import "class2.h"
@implementation class1
{
int saeid;
}
@synthesize table;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int x = (indexPath.row)+1;
saeid = x; //initialize global variable
NSLog(@"X & SAEID: %d & %d",x,saeid);
}
class2.h
#import "class1.h"
@interface class2 : UIViewController<UIScrollViewDelegate>
{
}
@end
class2.m
#import "class2.h"
@implementation class2
{
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"Saeid in class2 : %d",saeid);
}
答案 0 :(得分:1)
这里似乎有些混乱。最重要的是,全局变量不能“在”类中 - 全局变量根据定义在任何类之外。因此,如果您真的想要一个全局变量(稍后会详细介绍),那么您需要在类定义之外的class1.m中使用int saeid;
定义,并将其放在文件级别。
完成后,事情仍然无法编译。语句extern int saeid;
粗略地告诉编译器“我已经在其他地方定义了一个名为saeid的整数,所以只是假装它存在并让链接器弄清楚如何将它连接起来。”没有理由在class1.h中使用此语句,因为该全局变量未在该文件中的任何位置使用。相反,你应该把这个extern语句放在class2.m的顶部附近。它在该文件中使用,因此您需要向编译器保证变量是在编译该文件时定义的。
这些步骤应该让您的代码进行编译。但现在你应该停下来想想你是否真的想要一个全局变量。全局变量将您的类绑定在一起,并且很难在不影响(并可能破坏)其他类的情况下更改它们。它们使得测试代码变得更加困难,并且使得读取代码变得更加混乱。这里要考虑的另一个选择是在class1
类上创建saeid作为属性,并向class1*
添加class2
属性。然后,当您创建class2
实例时,请传递指向现有class1
实例的指针。 class2
实例可以保留该指针,并根据需要使用它来访问saeid属性。
答案 1 :(得分:0)
在Objectice-C中,你不能拥有类变量,只能拥有实例变量。
如果你想要一个全局变量,你可以写:
#import "class1.h"
#import "class2.h"
int saeid;
@implementation class1
{
}
@synthesize table;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int x = (indexPath.row)+1;
saeid = x; //initialize global variable
NSLog(@"X & SAEID: %d & %d",x,saeid);
}
但那只是一个全局变量,它与课程无关!