合成的目的

Jos*_*Kid 28 objective-c ios

我正在使用iOS5书来学习iOS编程.

@synthesize coolWord;
Run Code Online (Sandbox Code Playgroud)

^ synthesize用于.m文件中的所有属性

我听说在iOS6中不需要合成,因为它是自动完成的.这是真的?

合成是否对iOS6起任何作用?

谢谢你的澄清.:)

Fir*_*iro 34

objective-c中的@synthesize只实现属性设置器和getter:

- (void)setCoolWord:(NSString *)coolWord {
     _coolWord = coolWord;
}

- (NSString *)coolWord {
    return _coolWord;
}
Run Code Online (Sandbox Code Playgroud)

Xcode 4确实为您实现了这一点(iOS6需要Xcode 4).从技术上讲,它实现@synthesize coolWord = _coolWord(_coolWord是实例变量并且coolWord是属性).

要访问这些属性,请使用self.coolWord它们进行设置self.coolWord = @"YEAH!";和获取NSLog(@"%@", self.coolWord);

另请注意,setter和getter仍然可以手动实现.如果你实现了setter和getter,你需要手动包含@synthesize coolWord = _coolWord;(不知道为什么会这样).


Jan*_*ano 9

iOS6中的自动合成仍然需要 @synthesize

  • 为a中定义的属性生成存取方法@protocol.
  • 在包含自己的访问者时生成支持变量.

第二种情况可以这样验证:

#import <Foundation/Foundation.h>
@interface User : NSObject
@property (nonatomic, assign) NSInteger edad;
@end
@implementation User
@end
Run Code Online (Sandbox Code Playgroud)

键入:clang -rewrite-objc main.m并检查是否生成了变量.现在添加访问者:

@implementation User
-(void)setEdad:(NSInteger)nuevaEdad {}
-(NSInteger)edad { return 0;}
@end
Run Code Online (Sandbox Code Playgroud)

键入:clang -rewrite-objc main.m并检查是否未生成变量.因此,为了使用来自访问器的后备变量,您需要包含@synthesize.

它可能与有关:

Clang为声明属性的自动合成提供支持.使用此功能,clang提供了未声明@dynamic且没有用户提供的后备getter和setter方法的属性的默认合成.