在Objective-C中,为什么编译器在两个完全不同的视图控制器类中关注具有相同名称的变量?

时间:2020-12-14 16:50:00

I noticed that when I attempt to use the same variable name in different view controllers then the compiler will complain and won't build. Why does the compiler care about variables with the same name in two totally different view controllers? What brought me to this question is that I want to pass data from View Controller A to View Controller B in order to avoid making a 2nd network call in my app.

我注意到当我尝试在不同的视图控制器中使用相同的变量名时,编译器会抱怨并且不会构建。为什么编译器在两个完全不同的视图控制器中关注具有相同名称的变量?让我想到这个问题的原因是我想将视图控制器A中的数据传递给View Controller B,以避免在我的应用程序中进行第二次网络调用。

View Controller A:

查看控制器A:

#import "UIKit.h"

@interface MenuController ()<UITableViewDataSource ,UITableViewDelegate>


@end

@implementation MenuController

NSString *userFirstNameString;
NSString *userLastNameString;

@end

View Controller B:

查看控制器B:

#import "UIKit.h"

@interface MenuControllerB ()<UITableViewDataSource ,UITableViewDelegate>


@end

@implementation MenuControllerB

NSString *userFirstNameString;
NSString *userLastNameString;

@end

Screenshot of error: 在Objective-C中,为什么编译器在两个完全不同的视图控制器类中关注具有相同名称的变量?

错误的屏幕截图:

1 个解决方案

#1


1  

It's just a matter of knowing C. Objective-C is C.

这只是了解C. Objective-C是C的问题。

Think about the status (scope) of those NSString declarations. They are not instance properties. They are not locals. What do you suppose they are...?

考虑那些NSString声明的状态(范围)。它们不是实例属性。他们不是当地人。你认为他们是什么......?

That's right. They are globals. So there is only one namespace, and now you have conflicting global declarations.

那就对了。它们是全局的。所以只有一个命名空间,现在你有了冲突的全局声明。

To prevent that, declare the strings static. That is exactly what static is for, at file level: it prevents the declaration from leaking out into the global namespace.

为了防止这种情况,请将字符串声明为static。这正是静态用于文件级别的内容:它可以防止声明泄漏到全局命名空间中。

#1


1  

It's just a matter of knowing C. Objective-C is C.

这只是了解C. Objective-C是C的问题。

Think about the status (scope) of those NSString declarations. They are not instance properties. They are not locals. What do you suppose they are...?

考虑那些NSString声明的状态(范围)。它们不是实例属性。他们不是当地人。你认为他们是什么......?

That's right. They are globals. So there is only one namespace, and now you have conflicting global declarations.

那就对了。它们是全局的。所以只有一个命名空间,现在你有了冲突的全局声明。

To prevent that, declare the strings static. That is exactly what static is for, at file level: it prevents the declaration from leaking out into the global namespace.

为了防止这种情况,请将字符串声明为static。这正是静态用于文件级别的内容:它可以防止声明泄漏到全局命名空间中。