OC學習篇之---@property和@synthesize的使用,ocsynthesize

來源:互聯網
上載者:User

OC學習篇之---@property和@synthesize的使用,ocsynthesize

在之前一片文章我們介紹了OC中的記憶體管理:http://blog.csdn.net/jiangwei0910410003/article/details/41924683,今天我們來介紹兩個關鍵字的使用:@property和@synthesize


一、@property關鍵字

這個關鍵字是OC中能夠快速的定義一個屬性的方式,而且他可以設定一些值,就可以達到一定的效果,比如引用計數的問題

下面來看一下他的使用方法:

////  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方法了

第一步產生_userName屬性

第二步為_userName屬性自動產生set/get方法

這樣定義是不是比以前方便多了


下面再來看一下他還有三個值可以設定:

@property(atomic,retain,readwrite) Dog *dog;

1、第一個位置的值:

atomic:線程保護的,預設

nonatomic:線程不保護的

2、第二個位置的值:

assign:直接賦值,預設

retain:保留對象,內部會自動調用retain方法,引用計數+1

copy:拷貝對象

3、第三個位置的值:

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方法//這樣就比較費時,所以這時候就可以使用@propertyint 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;}
運行結果:




二、@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關鍵字,後面定義屬性的時候幾乎就是用它了,非常方便







聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.