一、主要屬性介紹
1、自動合成setter、getter方法
1)、接口部分@property指定屬性 2)、實作部分@synthesize
如果
@syntheszie widows = _windows
這裡成員變量名是_windows,而不是windows
2、atomic(nonatomic)
這裡主要是指存取方法為原子操作,實作線程安全,atomic是預設,保證線程安全,但是會導緻性能降低,單線程我們一般考慮nonatomic
3、copy
用這個修飾了屬性名,把副本值設定給類的屬性,如果指派的副本發生改變,但是類部的屬性值不會改變
4、getter、setter
如果(getter = ff1, setter = ff2),會把預設的getter方法改為ff1, 會把預設setter方法改為ff2,我們調用的時候就是[對象 ff1]、[對象 ff2]
5、readonly、readwirte
readonly是指系統指合成getter方法,不合成setter方法
readwirte是預設的,都合成
6、retain
使用retain訓示定義屬性時,當莫個對象指派給屬性時,該屬性原來所引用的對象引用計數減1,被指派對象的引用計數加1
當一個對象的引用計數大于1時,該對象不該被回收。
7、strong、weak
strong:指被指派對象持有強引用,不會自動回收
weak:使用弱引用指向被指派對象,該對象可能被回收
二、測試demo
User.h
#ifndef User_h
#define User_h
#import <Foundation/Foundation.h>
@interface User : NSObject
@property (nonatomic) NSString *name;
@property (nonatomic) NSString *city;
@property (nonatomic, copy) NSString *add;
@property NSString *pass;
@property NSDate *birth;
@property NSDate *birth1;
@end
#endif /* User_h */
User.m
#import <Foundation/Foundation.h>
#import "User.h"
@implementation User
@synthesize name = _name;
@synthesize pass;
@synthesize birth;
-(void) setName:(NSString *)name
{
self->_name = [NSString stringWithFormat:@"hello%@", name];
}
@end
main.m檔案
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "Person.h"
#import "Apple.h"
#import "User.h"
#import "Args.h"
#import "KVCPerson.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
User *user = [User new];
NSMutableString *name = [NSMutableString stringWithString:@"chencaifeng"];
NSMutableString *city = [NSMutableString stringWithString:@"hunan"];
NSMutableString *addr = [NSMutableString stringWithString:@"luyunlu"];
[user setName:name];
[user setCity:city];
[user setAdd:addr];
[user setPass:@"hello"];
[user setBirth:[NSDate date]];
NSLog(@"name is %@, and pass is %@, birth is%@, city is%@, add is %@", [user name], [user pass], [user birth], [user city], [user add]);
//我們把setName函數重寫了,雖然name後面追加了字元串,但是後面列印值沒有改變
[name appendString:@"chenyu"];
//由于這裡屬性沒有加copy,city後面追加了字元串,是以後面列印也變了
[city appendString:@"changsha"];
//由于這裡屬性加了copy,由于這個addr後面值追加了,是以後面列印不會改變
[addr appendString:@"kanyunlu"];
NSLog(@"name is %@, and pass is %@, birth is%@, city is%@, add is %@", [user name], [user pass], [user birth], [user city], [user add]);
//這裡是用.操作
user.add = @"hello";
NSLog(@"user add is %@", user.add);
}
}
三、運作結果
name is hellochencaifeng, and pass is hello, birth isFri Jul 6 19:51:04 2018, city ishunan, add is luyunlu
name is hellochencaifeng, and pass is hello, birth isFri Jul 6 19:51:04 2018, city ishunanchangsha, add is luyunlu
user add is hello