【问题标题】:instance variables in objective c .m file目标 c .m 文件中的实例变量
【发布时间】:2016-12-23 18:16:08
【问题描述】:

在Objective c中,实例变量var1var2有什么区别?

(此代码在一个 .m 文件中,如果 @interface 在头文件中而 @implementation 在实现文件中,这有什么区别吗?我的意思是与一个文件中的两个实例相比有什么区别变量。)

@interface MyService {
 NSString *var1;
}

@end

@implementation MyService {
 NSString *var2;
}
@end

【问题讨论】:

  • 你希望Leem.fin有什么解决方案?
  • 你明白我的回答吗?

标签: ios objective-c


【解决方案1】:

它们之间的区别在于可见性。 @interface 部分中定义的变量对任何导入接口的代码都是可见的。 @implementation 部分中声明的变量仅对类实现中的代码可见。

如果在实现文件中声明了@interface,则它的行为实际上与在@implementation 部分中声明它的行为相同。

【讨论】:

  • 我看不懂你的第二段,听起来像“如果在实现文件中声明了@interface,它与在实现文件中声明的一样”什么?您能否使用一些代码 sn-p 更清楚地解释?谢谢。
【解决方案2】:

实现中声明的实例变量是隐式的 隐藏(实际上是私有的)并且无法更改可见性 - @public、@protected 和 @private 不会产生编译器错误(带有 至少当前的 Clang)但被忽略。

你可以找到它here

【讨论】:

  • 关于在一个实现文件中定义的问题(@interface@implementation 就像我的代码显示VS 单独的文件、头文件和实现文件一样),它对var1 有什么影响吗?和 var 2
  • 就像 Avi 在可见性中告诉你的,这个变量将是 @public or @protected or @private,就这样 :)。
【解决方案3】:

我已经深入搜索了您的问题。Leem.fin 兄弟问得很好。我尝试了示例一

#import "SecondViewController.h"
@interface SecondViewController ()
{
    NSString *variableOne;
}
@end

@implementation SecondViewController
{
   NSString *variableTwo;
}

- (void)viewDidLoad
{
  [super viewDidLoad];
  // Do any additional setup after loading the view.
  [self setValueToString];
   NSLog(@"The variable One is - %@",variableOne);
   NSLog(@"The variable Two is - %@",variableTwo);
}

-(void)setValueToString
{
    variableOne = @"iOS";
    variableTwo = @"iPhone";
}

打印出来的结果是

 The variable One is - iOS
 The variable Two is - iPhone

但是当我尝试在 Class 方法中访问这些时

+(void)changeStrings
{
   variableOne = @"iPad"; //I get error here
   variableTwo = @"iMac"; //I get error here
}

错误显示

类方法中访问的实例变量'variableOne'

在类方法中访问的实例变量“variableTwo”

从上面的代码我明白了

都是实例变量

只能在实例方法中访问

它们之间没有区别

So Where to put

Difference between them

Difference between putting variable inside interface and implementation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 2013-02-02
    • 2023-04-04
    相关资源
    最近更新 更多