对@property与@synthesize的理解

先说IOS5以前代码:

#import "parentModel.h"

@interface subModel : parentModel
{
   //声明一个实例变量
    NSString *strA;
}
//声明一个strA属性 声明属性strA的set get方法
@property(strong, nonatomic)NSString *strA;
@end

@implementation subModel
//指定属性strA与实例变量strA对应 实现属性strA的set get方法
@synthesize strA;

@end

IOS5以后的代码:

@interface subModel : parentModel
/*
声明一个strA属性 并生成一个_strA实例变量 声明属性strA的set get方法
并在.m文件中实现属性strA的set get方法 指定属性strA与实例变量_strA对应
不再需要关键字@synthesize了
*/
@property(strong, nonatomic)NSString *strA;
@end

如果加上以下代码

@implementation subModel
//生成一个实例变量strA 指定属性strA与实例变量strA对应 实现属性strA的set get方法
@synthesize strA;
@end

@implementation subModel
//指定属性strA与实例变量_strA对应 实现属性strA的set get方法
@synthesize strA = _strA;
@end

如果想要重写set get方法 实现懒加载

@interface subModel : parentModel
//生成实例变量_strA 声明一个strA属性 声明属性strA的set get方法
@property(strong, nonatomic)NSString *strA;
@end

@implementation subModel
//指定属性strA与实例变量_strA对应 实现属性strA的set get方法
@synthesize strA = _strA;

- (void)setStrA:(NSString *)strA
{
    //添加代码
    _strA = strA;
}

- (NSString *)getStrA
{
    //添加代码
    return _strA;
}
@end

写点总结的东西

#import "parentModel.h"

@interface subModel : parentModel
@property(strong, nonatomic)NSString *strA;//写法一
@end


@interface parentModel ()
@property(strong, nonatomic)NSString *strB;//写法二
@end

@implementation subModel
{
    //写法三
    NSString *strC;
}
@synthesize strD = _strD;//写法四
@end

写法一:声明属性,方便外部文件存取,重写set 或 get方法
写法二:声明属性,指向私有实例变量,用于重写set 或 get方法 实现懒加载
写法三:声明私有实例变量,方便类中调用
写法四:一般情况是不用写的,当需要同时重写set和get方法的时候就需要@synthesize 实现属性指向

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,860评论 25 709
  • 人永远需要反照并证明自己的自体客体(意即重要他人)。 ——南希·麦克威廉斯的《精神分析案例解析》 今天读心理学家武...
    小壹Odelia阅读 774评论 0 0
  • 秋来疾雨桂暗香 静观池满羡鱼漾 想学垂纶天难料 漫天云雾青山罩
    得一生二阅读 287评论 0 1