一、什么是成員變量腊脱、屬性访得、實(shí)例變量?
@interface ViewController : UIViewController
{
NSString *string1;
NSString *_string2;
int count;
float value;
}
@property (nonatomic, copy) NSString *string3;
@end
上訴例子中:
成員變量: string1陕凹、_string2悍抑、count、value
屬性: string3
實(shí)例變量: string1杜耙、_string2
可以看到在 { } 中所聲明的所有變量都是成員變量搜骡,所以string1、_string2泥技、count浆兰、value都是成員變量磕仅;
因?yàn)閷?shí)例是針對類而言珊豹,實(shí)例是類的聲明,所以只有string1榕订、_string2是實(shí)例變量店茶;
屬性就是用@property修飾的變量,即string3劫恒。
成員變量 = 實(shí)例變量 + 基本數(shù)據(jù)類型變量
二贩幻、下面列舉各種不同情況下的使用
@interface ViewController : UIViewController
@property (nonatomic, copy) NSString *string;
@end
正常情況下會自動給string生成_string實(shí)例變量轿腺、setter和getter方法,通過_string和self.string獲取變量丛楚;
如果
@synthesize string = _string;
與上面相同族壳;如果
{ NSString *_string; }
與上面相同;如果
@synthesize string;
則不會自動生成_string實(shí)例變量趣些,通過string和self.string獲取變量仿荆;如果
@synthesize string = string;
與上面相同;如果
{ NSString *string; }
會自動生成_string實(shí)例變量坏平,但實(shí)例變量string和屬性string不是同一個變量拢操,前者通過string和self->string獲取,后者通過_string和self.string獲炔疤妗令境;
string = @"11";
_string = @"22";
NSLog(@"%@ %@", string, self.string);
結(jié)果:11 22
如果
{ NSString *string; }
并且@synthesize string;
則不會自動生成_string實(shí)例變量,通過string和self.string獲取變量顾瞪;如果
{ NSString *_string; }
并且@synthesize string;
則_string與self.string不是同一個變量舔庶,string與self.string同一個變量;
_string = @"11";
string = @"22";
NSLog(@"%@ %@", _string, self.string);
結(jié)果:11 22
總結(jié):屬性如果不用@synthesize修飾玲昧,則會默認(rèn)生成帶下劃線的成員變量栖茉;如果用了@synthesize,若是用 @synthesize 屬性名; 或者 @synthesize 屬性名 = 屬性名; 則不會生成帶下劃線的屬性名的成員變量孵延,若用 @synthesize 屬性名 = _屬性名; 與正常情況相同吕漂。
若聲明了同名的不帶下劃線的成員變量,且沒有用@synthesize修飾讓該屬性與該成員變量相等尘应,則兩者是不同的變量惶凝。