IOS之学习笔记五(合成存取方法)
一、主要屬性介紹
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]; } @endmain.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
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的IOS之学习笔记五(合成存取方法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IOS之提示Interface type
- 下一篇: IOS之学习笔记六(可变形参)