iOS之變數定義使用

來源:互聯網
上載者:User

iOS之變數定義使用

還是以例子來說明吧。建立一個ViewController類,Xcode為我們自動產生了兩個檔案:ViewController.h 和 ViewController.m

1、成員變數

 

@interface ViewController : UIViewController {    // 我們稱myTest1為成員變數    BOOL myTest1;}@end

@implementation ViewController- (void)viewDidLoad {    myTest1 = NO; // 不支援self.myTest1  或  [self myTest1] 的用法}@end

成員變數不使用 @synthesize,這個屬性是私人屬性,不斷給它賦值時不會改變引用計數,

 

成員變數預設是protected,一般情況下,非子類對象無法訪問。

 

2、類擴充的成員變數

 

@interface ViewController : UIViewController@end

// 類擴充都是放在.m檔案中@implementation的上方,否則會抱錯@interface ViewController () {    // 類擴充的成員變數    BOOL myTest2;}@end@implementation ViewController- (void)viewDidLoad {    myTest2 = YES; // 用法與1相同}@end

其實這種表達方式與1是一樣的,區別在於更好的隱藏了.h檔案的私人資訊。

 

 

 

3、屬性變數

 

@interface ViewController : UIViewController// 屬性變數,若不使用 @synthesize 只表示是public屬性@property (nonatomic, copy) NSString *str1;@end

@implementation ViewController@synthesize str1 = _str1; // 合成getter和setter,放在@implementation內- (void)viewDidLoad {    // 不存在的用法,直接報錯    str1 = @abc;        // 正確用法1    _str1 = @abc; // 屬性名稱加前_表示公有屬性,在 @property 聲明時系統會自己加    // 正確用法2    NSString *astr = [self str1];    NSLog(@%@, astr);    // 正確用法3    self.str1 = @123;}@end

4、類擴充的成員變數

 

 

@interface ViewController : UIViewController@end

 

 

 

@interface ViewController ()   // 類擴充的屬性變數   @property (nonatomic, copy) NSString *str1;@end@implementation ViewController   @synthesize str1 = _str1; // 沒意義- (void)viewDidLoad {    // 錯誤的用法    str1 = @345;        // 正確用法    self.str1 = @123;        // 正確用法    _str1 = @678;        // 正確用法    NSString * aStr = [self str1];}@end

沒有@synthesize其實作用一樣,因為str1沒有經過.h對開公開。類擴充中定義的@property的作用無非是使用self.str1 和 [self str1] 更方便些。

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.