我正在使用一本 iOS5 书籍来学习 iOS 编程。
@synthesize coolWord;
^synthesize 用于 .m 文件中的所有属性
我听说在 iOS6 中不需要合成,因为它会自动为你完成。这是真的?
合成对 iOS6 有什么作用吗?
感谢您的澄清。:)
我正在使用一本 iOS5 书籍来学习 iOS 编程。
@synthesize coolWord;
^synthesize 用于 .m 文件中的所有属性
我听说在 iOS6 中不需要合成,因为它会自动为你完成。这是真的?
合成对 iOS6 有什么作用吗?
感谢您的澄清。:)
Objective-c 中的@synthesize 只是实现了属性设置器和获取器:
- (void)setCoolWord:(NSString *)coolWord {
_coolWord = coolWord;
}
- (NSString *)coolWord {
return _coolWord;
}
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;
(不知道为什么会这样)。
iOS6 中的自动合成仍然需要@synthesize
@protocol
。第二种情况可以这样验证:
#import <Foundation/Foundation.h>
@interface User : NSObject
@property (nonatomic, assign) NSInteger edad;
@end
@implementation User
@end
键入:clang -rewrite-objc main.m
并检查是否生成了变量。现在添加访问器:
@implementation User
-(void)setEdad:(NSInteger)nuevaEdad {}
-(NSInteger)edad { return 0;}
@end
键入:clang -rewrite-objc main.m
并检查该变量是否未生成。因此,为了使用访问器中的支持变量,您需要包含@synthesize
.
它可能与此有关:
Clang 提供对声明属性的自动合成的支持。使用此功能,clang 提供了那些未声明 @dynamic 并且没有用户提供支持 getter 和 setter 方法的属性的默认合成。
我不确定它@synthesize
与 iOS6 有什么关系,但从 Xcode 4.0 开始,它基本上已被弃用。基本上,你不需要它!只需使用@property
声明,在幕后,编译器会为您生成它。
这是一个例子:
@property (strong, nonatomic) NSString *name;
/*Code generated in background, doesn't actually appear in your application*/
@synthesize name = _name;
- (NSString*)name
{
return _name;
}
- (void) setName:(NSString*)name
{
_name = name;
}
所有这些代码都由编译器为您处理。因此,如果您的应用程序具有@synthesize
,是时候进行一些清理了。
您可以在此处查看我的类似问题,这可能有助于澄清。
我相信@synthesize
指令会自动插入最新的 Obj-C 编译器(iOS 6 附带的编译器)。
@synthesize pre-iOS 6 的重点是自动为实例变量创建 getter 和 setter,以便生成[classInstance getCoolWord]
和[classInstance setCoolWord:(NSString *)aCoolWord]
。因为它们是用 声明的@property
,所以您还可以获得 getter 和 setter 的点语法的便利。
hope this will help little more
yes previously we have to synthesis the property by using @synthesis now it done by IDE itself.
但我们可以像这样使用它
// IDE 在内部做什么
@synthesis name=_name;
我们使用 _name 来访问特定的属性,但现在您希望通过其他方式(例如 firstname)进行合成,您可以这样做
@synthesis name= firstname
或者只是名字
@synthesis name=name
在 iOS6 中使用自动合成,不再需要专门声明支持 ivars 或编写 @synthesize 语句。当编译器找到@property 语句时,它将使用我们刚刚查看的指南代表我们执行这两项操作。所以我们需要做的就是声明一个这样的属性:
@property (nonatomic, strong) NSString *abc;
而在 iOS 6 中,@synthesize abc = _abc 将在编译时自动添加。