【问题标题】:get error when to use global Variable使用全局变量时出错
【发布时间】:2013-04-07 08:03:27
【问题描述】:

我的程序中有 2 节课 第一类是class1,第二类是class2。我想在类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);

}

【问题讨论】:

    标签: ios objective-c global-variables


    【解决方案1】:

    这里似乎有些混乱。最重要的是,全局变量不能“在”类中——根据定义,全局变量在任何类之外。因此,如果您真的想要一个全局变量(稍后会详细介绍),那么您需要将 class1.m 中的 int saeid; 定义放在类定义之外,并将其放在文件级别。

    完成之后,事情仍然无法编译。语句extern int saeid; 粗略地对编译器说:“我在其他地方定义了一个名为 saeid 的整数,所以假装它存在,让链接器弄清楚如何连接它。”没有理由在 class1.h 中有这个语句,因为这个全局变量在该文件的任何地方都没有使用。相反,您应该将此 extern 语句放在 class2.m 的顶部附近。它在该文件中使用,因此您需要确保编译器在编译该文件时在某处定义了该变量。

    这些步骤应该可以编译您的代码。但是现在你应该停下来想想你是否真的想要一个全局变量。全局变量将您的类联系在一起,并且很难在不影响(并可能破坏)其他类的情况下进行更改。它们使测试代码变得更加困难,并且使阅读代码更加混乱。这里要考虑的另一个选项是在class1 类上创建saeid 作为属性,并将class1* 属性添加到class2。然后,当您创建 class2 实例时,传递一个指向现有 class1 实例的指针。 class2 实例可以保留该指针并根据需要使用它来访问 saeid 属性。

    【讨论】:

    • 我的朋友你能解释一下吗?有代码我英语不好。
    【解决方案2】:

    在 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);
    }
    

    但这只是一个全局变量,与类无关!

    【讨论】:

    • 我想在 class1 中获取该全局变量的值并在 class2 中使用该值
    • 您的代码没有显示类或序列的分配。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    相关资源
    最近更新 更多