#import <Foundation/Foundation.h>
@interface Person : NSObject
@property NSString * name;
@end
这样就直接能使用p.name了。
好像不需要如下定义:
#import <Foundation/Foundation.h>
@interface Person : NSObject{
NSString* _name;
}
@property NSString * name;
@end
这两种方式有啥区别呢?
天蓬老师2017-04-24 09:16:09
From my experience, it is recommended to use property to define all names, so that the variable memory operation method can be clearly distinguished (multi-threading is too rare and can be ignored). And, for me, this is one of the easier ways to identify global variables. Using _name directly in the m file can quickly understand that this is a global variable. I think it is a very good habit to use properties as global variables. In addition, the synthesissize mentioned by @freewolf here can actually be omitted. Here is a simple setter as an example.
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic,retain) NSString * name;
@end
#import "Person.h"
@implementation Person
//下一步可以省略
@synthesize name = _name;
-(void) setName:(NSString *)name
{
name = _name;
}
@end
PHP中文网2017-04-24 09:16:09
@property NSString * name;
// 这个等于下面的(编译器会自动帮你处理)
//.h文件
{
NSString *_name;
}
// (线程处理方式, 内存操作方式)
@property(atomic, copy) NSString * name;
// .m文件
// 属性名对应的成员变量是
@synthesize _name = name;