當前位置:
首頁 >
IOS第三天(@property与@synthesize的用法)
發布時間:2025/6/17
47
豆豆
生活随笔
收集整理的這篇文章主要介紹了
IOS第三天(@property与@synthesize的用法)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、@property與@synthesize基本規范用法
1.@property
當編譯器遇到@property時,會自動展開成getter和setter的聲明
#import <Foundation/Foundation.h>@interface Student : NSObject {int _age;int _no;float _height; }// 當編譯器遇到@property時,會自動展開成getter和setter的聲明 @property int age; //- (void)setAge:(int)newAge; //- (int)age; @property int no; //- (void)setNo:(int)newNo; //- (int)no; @property float height; //- (void)setHeight:(float)newHeight; //- (float)height;- (void)test; @end?
?
2.@synthesize
@synthesize會自動生成getter和setter的實現
#import "Student.h"@implementation Student// @synthesize age, height, no;// @synthesize會自動生成getter和setter的實現// @synthesize默認會去訪問跟age同名的變量 // 如果找不到同名的變量,會自動生成一個私有的同名變量age // @synthesize age;// age = _age代表getter和setter會去訪問_age這個成員變量 @synthesize age = _age; //- (void)setAge:(int)newAge { // _age = newAge; //} // //- (int)age { // return _age; //}@synthesize height = _height; //- (void)setHeight:(float)newHeight { // _height = newHeight; //} // //- (float)height { // return _height; //}@synthesize no = _no; //- (void)setNo:(int)newNo { // _no = newNo; //} // //- (int)no { // return _no; //}- (void)test {_age = 10;_height = 10.0f;_no = 10;} @end?
?
二、@property與@synthesize進階用法
Person.h
#import <Foundation/Foundation.h>@interface Person : NSObject {int _ID;float _weight; }@property int ID;@property float weight;@end?
Person.m
#import "Person.h"@implementation Person@synthesize ID = _ID; @synthesize weight = _weight;//- (void)setWeight:(float)weight { // _weight = weight * 1000; //}//- (float)weight { // return _weight * 1000; //} @end?
三、@property與@synthesize終極用法
Teacher.h
#import <Foundation/Foundation.h>@interface Teacher : NSObject@property int age; @endTeacher.m
#import "Teacher.h"@implementation Teacher// 在xcode4.5的環境下,可以省略@synthesize,并且默認會去訪問_age這個成員變量 // 如果找不到_age這個成員變量,會自動生成一個叫做_age的私有成員變量-(void)test {_age = 10; } @end?四、測試:
main.m
#import <Foundation/Foundation.h> #import "Student.h"#import "Teacher.h"int main(int argc, const char * argv[]) {@autoreleasepool {Teacher *tea = [[Teacher alloc] init]; //用Teacher類創建對象 tea.age = 10; //調用setAge方法,將10賦值給_age NSLog(@"age is %i", tea.age); //打印tea對象里的_age [tea release]; //創建對象后的內存回收機制 }return 0; }?
轉載于:https://www.cnblogs.com/zhmnda/p/4855925.html
總結
以上是生活随笔為你收集整理的IOS第三天(@property与@synthesize的用法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 119. Pascal's Triang
- 下一篇: CentOS6.6配置iptables