PS:記錄自己工作學(xué)習(xí)中的一些知識劝萤;
1.@property是什么?
@property是聲明屬性的語法,是一個(gè)編譯器指令攘宙,它可以快速方便的為一個(gè)實(shí)例變量創(chuàng)建setter/getter,并允許我們用點(diǎn)語法使用。
2.傳統(tǒng)的setter/getter方法.
Student.h
#import <Foundation/Foundation.h>
@interface Student : NSObject {
// 定義成員變量 姓名
NSString *name;
}
// 聲明成員變量name的set方法
- (void)setName:(NSString *)newName;
// 聲明成員變量name的get方法
- (NSString *)name;
@end
</code></pre>
Student.m
#import "Student.h"
@implementation Student
// 實(shí)現(xiàn)set方法
- (void)setName:(NSString *)newName {
name = newName;
}
// 實(shí)現(xiàn)get方法
- (NSString *)name {
return name;
}
@end
</code></pre>
main.m
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
Student *stu = [[Student alloc]init];
// 設(shè)置name
[stu setName:@"tnan"];
NSLog(@"My name is %@",[stu name]);
}
return 0;
}
</code></pre>
輸出:基礎(chǔ)知識之@property[1298:113851] My name is tnan
3.使用@property代替?zhèn)鹘y(tǒng)的set/get方法
.h
#import <Foundation/Foundation.h>
@interface Student : NSObject {
// 定義成員變量 姓名
NSString *name;
}
// 使用@property聲明name
@property (nonatomic, strong)NSString *name;
// 聲明成員變量name的set方法
- (void)setName:(NSString *)newName;
// 聲明成員變量name的get方法
- (NSString *)name;
@end
////////////////////
.m
#import "Student.h"
@implementation Student
//方便我們看清楚是否調(diào)用set/get加入NSLog(@"%s",__func__);
// 實(shí)現(xiàn)set方法
- (void)setName:(NSString *)newName {
name = newName;
NSLog(@"%s",__func__);
}
// 實(shí)現(xiàn)get方法
- (NSString *)name {
NSLog(@"%s",__func__);
return name;
}
@end
////////////////////
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
Student *stu = [[Student alloc]init];
// 設(shè)置name
// [stu setName:@"tnan"];
stu.name = @"tnan";
NSLog(@"My name is %@",[stu name]);
}
return 0;
}
輸出:
基礎(chǔ)知識之@property[1413:120618] -[Student setName:]
基礎(chǔ)知識之@property[1413:120618] -[Student name]
基礎(chǔ)知識之@property[1413:120618] My name is tnan
很明顯先set后get,一目了然模聋。
最終代碼是這樣的,簡潔肩民,方便
.h
#import <Foundation/Foundation.h>
@interface Student : NSObject
// 使用@property聲明name
@property (nonatomic, strong)NSString *name;
@end
////////////////////
.m
#import "Student.h"
@implementation Student
@end
////////////////////
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
Student *stu = [[Student alloc]init];
// 設(shè)置name
stu.name = @"tnan";
NSLog(@"My name is %@",[stu name]);
}
return 0;
}
</code></pre>