在以前一片文章咱們介紹了OC中的內存管理:http://blog.csdn.net/jiangwei0910410003/article/details/41924683,今天咱們來介紹兩個關鍵字的使用:@property和@synthesizejava
1、@property關鍵字atom
這個關鍵字是OC中可以快速的定義一個屬性的方式,並且他能夠設置一些值,就能夠達到必定的效果,好比引用計數的問題spa
下面來看一下他的使用方法:.net
// // Person.h // 25_Property // // Created by jiangwei on 14-10-12. // Copyright (c) 2014年 jiangwei. All rights reserved. // #import <Foundation/Foundation.h> @interface User : NSObject{ //NSString *_userName; //NSString *_passWord; //... } //第一步生成_userName屬性 //第二步爲_userName屬性自動生成set/get方法 //property在生成的set方法中,有沒有作引用的操做? //set方法的三種方式: //第一種方式: //普通賦值 //通常對象類型的引用操做 //NSString對象類型的引用操做 //第一個位置 //atomic:線程保護的,默認 //nonatomic:線程不保護的 //第二個位置 //assign:直接賦值,默認 //retain:保留對象 //copy:拷貝對象 //第三個位置 //readwrite:生成get/set方法,默認 //readonly:只生成get方法@property NSString *userName;
@end
還記得咱們以前定義屬性的時候,在{...}中進行定義,並且定義完以後還有可能須要實現get/set方法,這裏咱們直接使用@property關鍵字進行定義:線程
@property NSString *userName;這樣定義完以後,咱們就可使用這個屬性了:
這樣定義的方式以後,這個屬性就會自動有set/get方法了code
第一步生成_userName屬性對象
第二步爲_userName屬性自動生成set/get方法blog
這樣定義是否是比之前方便多了下面再來看一下他還有三個值能夠設置:ip
@property(atomic,retain,readwrite) Dog *dog;
一、第一個位置的值:內存
atomic:線程保護的,默認
nonatomic:線程不保護的
二、第二個位置的值:
assign:直接賦值,默認
retain:保留對象,內部會自動調用retain方法,引用計數+1
copy:拷貝對象
三、第三個位置的值:
readwrite:生成get/set方法,默認
readonly:只生成get方法
這裏來作一個例子:
main.m
// // main.m // 25_Property // // Created by jiangwei on 14-10-12. // Copyright (c) 2014年 jiangwei. All rights reserved. // #import <Foundation/Foundation.h> #import "User.h" #import "Dog.h" //當一個類中有不少個屬性的時候,那麼咱們須要手動的編寫他們的set/get方法 //這樣就比較費時,因此這時候就可使用@property int main(int argc, const char * argv[]) { User *user = [[User alloc] init]; Dog *dog = [[Dog alloc] init]; NSLog(@"count:%ld",[dog retainCount]); [user setDog:dog]; NSLog(@"count:%ld",[dog retainCount]); return 0; }運行結果:
2、@synthesize關鍵字
// // Person.m // 25_Property // // Created by jiangwei on 14-10-12. // Copyright (c) 2014年 jiangwei. All rights reserved. // #import <Foundation/Foundation.h> #import "User.h" //有時候咱們不想定義屬性爲_開頭的 //這時候咱們就可使用@synthesize,來修改咱們想要的屬性名 //這時候屬性_userName變成了$userName @implementation User @synthesize userName = $userName; @end由於咱們使用@property定義屬性以後,若是咱們想修改這個屬性的名稱,就可使用@synthesize關鍵字來對屬性名稱進行修改
@synthesize userName = $userName;
這一篇主要介紹了兩個關鍵字的使用,@property和@synthesize,特別是@property關鍵字,後面定義屬性的時候幾乎就是用它了,很是方便