iOS學習 --- 成員變量,實例變量,屬性

  • 成員變量: 

 

  1. 成員變量用於類內部,無需與外界接觸的變量,也就是所謂的類的私有變量
  2. 默認是 @proteced 修飾的。
  3. 成員變量不會自動生成set /get方法,需要自己手動實現。
  4. 成員變量不能用點語法,因爲沒有set/get方法,只能使用 -> 調用。
  5. 在{ }中聲明的變量都是成員變量,如果變量的數據類型是一個類,則稱這個變量爲實例變量,因此實例變量是成員變量的一種特殊情況。

 分析下面代碼:

@interface MyViewController :UIViewController
{
    //成員變量,實例變量
    UIButton *yourButton; 
    //成員變量
    int count; 
    //成員變量,實例變量
    id data; 
} 

 

  1.  在{ }中聲明的變量都是成員變量,所以上面yourButton,count,data都是成員變量。
  2. yourButton的數據類型是 UIButton ,是類,所以yourButton也是實例變量;id是OC特有的類,本質上講id等同於(void *),所以id data 屬於實例變量。????? 
  •    屬性:
  1. 屬性變量是用於和其他對象交互的變量,屬性變量的好處就是允許讓其他對象訪問該變量(因爲屬性創建的過程中自動生成了set 和get方法)。
  2. 對於屬性變量,一般把需要與外部接觸的變量定義在.h文件中,只在本類中使用的變量定義在.m文件中。
  3. 屬性的默認修飾符是 @protected 。
  4. 屬性會自動生成set 和get 方法。
  5. 屬性可以用點語法調用,點語法實際上調用的是set和get方法。
  6. 用 @property 聲明的屬性,編譯器會自動生成一個以 下劃線開頭的實例變量。

分析下面代碼 

@interface MyViewController :UIViewController
//屬性變量
@property (nonatomic, strong) UIButton *myButton;

@end
  1. 上面代碼聲明的屬性myButton,在創建的時候編譯器會自動生成一個實例變量 _myButton ,同時也會自動生成set和get方法,不需要自己手動再去寫實例變量,也不需要在 .m 文件中寫 @synthesize myButton 。
  2. 如果在.m中寫了@synthesize myButton ,那麼生成的實例變量就是myButton,如果沒寫@synthesize myButton,那麼生成的實例變量就是_myButton。

注意:

@synthesize的作用:

(1)讓編譯器爲你自動生成setter與getter方法。

(2)可以指定與屬性對應的實例變量,例如@synthesize myButton = xxx;那麼self.myButton其實是操作的實例變量xxx,而不是_myButton了。

  •  實例變量 
  1. 實例變量本質上就是成員變量,只是實例變量是針對類而言的。
  2. 實例變量是由類定義的變量,除去基本數據類型 int float ...等,其他類型的變量都叫做實例變量。
  3. *** 實例變量 + 基本數據類型變量 = 成員變量
  • 類別中的屬性(重點)

類別中只能添加實例方法、類方法、屬性,甚至可以實現協議,不能添加實例變量(或者說成員變量)。

經常會在類別中看到類似下面的代碼,在類別中用@property添加屬性aKeyPushView和aKeyButton,這種情況下不能生成對應的實例變量_aKeyPushView和_aKeyButton,也不能生成get和set方法。所以儘管添加了屬性,也不能點語法調用get和set方法。

#import "AppDelegate.h"

@interface AppDelegate (XGPush)
//推送
//聲明屬性
@property (nonatomic, strong) UIView *aKeyPushView;
@property (nonatomic, strong) UIbutton *aKeyButton;

/**
 XGPush 註冊
 @param launchOptions 啓動項
 */
-(void)registerXGPush:(NSDictionary *)launchOptions;

@end

****注意一點,匿名類別(匿名擴展)是可以添加實例變量的,非匿名類別是不能添加實例變量的,只能添加方法,或者屬性(其實也是方法),常用的擴展是在.m文件中聲明私有屬性和方法。 Category理論上不能添加變量,但是可以使用Runtime機制來彌補這種不足。????

 

#import "AppDelegate+XGPush.h"
@interface AppDelegate ()


@end

@implementation AppDelegate (XGPush)


#pragma mark --- Associated Object
-(void)setAKeyPushView:(UIView *)aKeyPushView{
    objc_setAssociatedObject(self, @selector(aKeyPushView), aKeyPushView,OBJC_ASSOCIATION_RETAIN);
}

-(UIView *)aKeyPushView{
    return  objc_getAssociatedObject(self, @selector(aKeyPushView));
}
-(void)setAppProgressView:(UIButton *)aKeyButton{
    objc_setAssociatedObject(self, @selector(aKeyButton), aKeyButton,OBJC_ASSOCIATION_RETAIN);
}

-(UIButton *) aKeyButton{
    return  objc_getAssociatedObject(self, @selector(aKeyButton));
}

相關文章:

iOS成員屬性和成員變量的區別

iOS中成員變量和屬性

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章