2014-01-25 61 views
-1

我是iOS新手,已经从教程和我的教授那里学习。
.h文件有:@synthesize与自我使用

@interface ViewController : UIViewController <UITextFieldDelegate> 

@property (strong, nonatomic) IBOutlet UILabel *myResponse; 
@property (strong, nonatomic) IBOutlet UITextField *myInput; 

@end 

.m文件有:

@sysnthesize myResponse 
@synthesize myInput 

我的问题是这样的:有什么区别,在.m文件,添加的@synthesize和然后使用诸如[myInput <do something here>]之类的属性与删除@synthesize并使用[self.myInput <do something here>]。我在Xcode 5上运行,所以我明白我有自动综合可用,但是两者之间有更细微的差别吗?

我的教授使用了@synthesize,我接下来的教程只是使用self.propertyName,因此我很好奇。

谢谢。

+0

如果您刚开始学习,最好阅读Apple文档以获取大多数基本问题:https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html –

+3

和不要再使用@synthesize –

回答

5

您不再需要明确使用@synthesize作为属性。如果你的教授正在使用它,那只是为了明确并展示底下发生了什么。

如果您的属性是在.h文件中定义的,则会自动生成访问器,变体和实例变量。如果您明确指出@synthesize这些属性,则可通过指令后提供的任何ivar名称访问它们。如果未使用@synthesize,则自动生成的ivars可通过_somePropertyName获得。

在您的示例中,使用@synthesize,可通过实例变量myResponse访问myResponse UILabel。如果没有@synthesize,则可通过_myResponse获得。在这两种情况下,都可以通过self.myResponse获得。在所有生命周期方法,访问器或增变器(-viewDidLoad-viewWillAppear,-setMyResponse:等)中使用实例变量并在所有其他方法中使用self.propertyName以清楚地区分类和实例变量的属性是最佳实践。