合成的目的
我正在使用iOS5书籍来学习iOS编程。
@synthesize coolWord;
^合成用于.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
是实例variables, coolWord
是属性)。
要访问这些属性使用self.coolWord
都设置self.coolWord = @"YEAH!";
并获得NSLog(@"%@", self.coolWord);
另外请注意,setter和getter仍然可以手动执行。 如果你实现了两个setter和getter,尽pipe你还需要手动包含@synthesize coolWord = _coolWord;
(不知道这是为什么)。
iOS6中的自动合成仍然需要@synthesize
- 为
@protocol
定义的属性生成访问器方法。 - 在包含自己的访问器时生成一个备份variables。
第二种情况可以这样validation:
#import <Foundation/Foundation.h> @interface User : NSObject @property (nonatomic, assign) NSInteger edad; @end @implementation User @end
键入: clang -rewrite-objc main.m
并检查variables是否生成。 现在添加访问器:
@implementation User -(void)setEdad:(NSInteger)nuevaEdad {} -(NSInteger)edad { return 0;} @end
键入: clang -rewrite-objc main.m
并检查variables是否未生成。 所以为了使用访问器的后备variables,你需要包含@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的一点是自动为实例variables创buildgetter&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来访问特定的属性,但现在你想通过其他方式来合成,比如名字,你可以这样做
@synthesis name= firstname
或者只是通过名字
@synthesis name=name
使用iOS6中的自动合成function,不再需要专门声明支持ivars或编写@synthesize语句。 当编译器find@property语句时,它将代表我们使用我们刚刚审查的指导方针。 所以我们需要做的是声明一个属性如下:
@property (nonatomic, strong) NSString *abc;
在iOS 6中,@synthesize abc = _abc将在编译时自动添加。