IOS之學(xué)習(xí)筆記五(合成存取方法)
一、主要屬性介紹
1、自動合成setter、getter方法
1)、接口部分@property指定屬性 2)、實現(xiàn)部分@synthesize
如果
@syntheszie widows = _windows
這里成員變量名是_windows,而不是windows
2、atomic(nonatomic)
這里主要是指存取方法為原子操作,實現(xiàn)線程安全,atomic是默認(rèn),保證線程安全,但是會導(dǎo)致性能降低,單線程我們一般考慮nonatomic
3、copy
用這個修飾了屬性名,把副本值設(shè)置給類的屬性,如果賦值的副本發(fā)生改變,但是類部的屬性值不會改變
4、getter、setter
如果(getter = ff1, setter = ff2),會把默認(rèn)的getter方法改為ff1, 會把默認(rèn)setter方法改為ff2,我們調(diào)用的時候就是[對象 ff1]、[對象 ff2]
5、readonly、readwirte
readonly是指系統(tǒng)指合成getter方法,不合成setter方法
readwirte是默認(rèn)的,都合成
6、retain
使用retain指示定義屬性時,當(dāng)莫個對象賦值給屬性時,該屬性原來所引用的對象引用計數(shù)減1,被賦值對象的引用計數(shù)加1
當(dāng)一個對象的引用計數(shù)大于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函數(shù)重寫了,雖然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);
}
}
三、運行結(jié)果
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
作者:chen.yu
深信服三年半工作經(jīng)驗,目前就職游戲廠商,希望能和大家交流和學(xué)習(xí),
微信公眾號:編程入門到禿頭 或掃描下面二維碼
零基礎(chǔ)入門進(jìn)階人工智能(鏈接)