objective-c - OC 直接使用@property就能定义属性了吗?
ringa_lee
ringa_lee 2017-04-24 09:14:09
0
2
450
#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

这两种方式有啥区别呢?

ringa_lee
ringa_lee

ringa_lee

reply all(2)
Peter_Zhu

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
洪涛

@property  NSString * name;
// 这个等于下面的(编译器会自动帮你处理)


//.h文件
{
    NSString *_name;
}
// (线程处理方式, 内存操作方式)
@property(atomic, copy)  NSString * name;

// .m文件
// 属性名对应的成员变量是
@synthesize _name = name;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template