欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

IOS第三天(@property与@synthesize的用法)

发布时间:2025/6/17 编程问答 49 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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; @end

  Teacher.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的用法)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。