【发布时间】:2013-02-28 07:23:22
【问题描述】:
我是 Objective C 和 iOS 的新手,目前正在尝试使用 iOS 6 SDK 学习应用程序开发。我真的无法理解的一个概念是在 .m 文件中访问时“_variable”和“self.variable”之间的区别。他们是一样的吗?还是不一样?
以下是一个简单的示例
MyClass.h
#import <Foundation/Foundation.h>
@interface MyClass : NSObject
@property (strong, nonatomic) NSString *myName;
@end
MyClass.m
#import "MyClass.h"
@interface MyClass ()
@property (nonatomic, strong) NSString *anotherName;
@end
@implementation MyClass
- (void) myFunction {
_myName = @"Ares";
self.myName = @"Ares";
_anotherName = @"Michael";
self.anotherName = @"Michael";
}
@end
那么上面设置变量的实现有区别吗? 变量“myName”是 Public 而“anotherName”是 Private。
非常感谢任何意见。谢谢!
【问题讨论】:
-
其实这个问题不是重复的。作为初学者,我搜索了 _variable 和 self.variable 之间的区别。我会忽略不使用下划线的问题,所以这对我来说是唯一的问题。但是,@Josh,无论如何,你的评论帮助了我,让我明白它们是一回事。
-
下划线丝毫不会改变 ivars 的性质或功能:How does an underscore in front of a variable in a Cocoa/ObjC class work?
标签: objective-c variables ios6