ios笔记--OC常用语法归纳小结
来源:互联网 发布:淘宝v2贷款5 15万 编辑:程序博客网 时间:2024/05/20 13:36
1、set,get方法
stu.age = 10; //等价于[stu setAge:10],编译器编译时会把该句自动转换[stu setAge:10]。
int age = stu.age;//等价于int age = [stu age];
2、释放对象内存
Student *stu =[ [Student alloc] init];
[stu release];
上面这两句等价于Student *stu =[[[Student alloc] init] autolease];
说明:释放对象都需要调用release方法,只是静态方法已经封装了autolease方法,不用我们去再次去调用release方法了,但是自己创建的对象,还需要手动管理内存,所以要手动调用一次release方法。
3、新建对象
Student *student = [Student new];
等价于 Student *student = [[Student alloc] init];
4、set,get方法的另一种写法
在.h声明文件中:
#include<Foundation/Foundation.h>
@interface Student : NSObject{
int age;
int no;
float heigh;
}
-(void)setAge:(int) newNo;
-(int)age;
-(void)setNo:(int) newNo;
-(int)no;
-(void)setHeight:(float)newHeight;
-(float)height;
@end
等价于以下写法
#include<Foundation/Foundation.h>
@interface Student : NSObject{
int age;
int no;
float height;
}
@property int age;//当编译器遇到@property时,会自动展开成age的getter和setter的声明
@property int no;
@property float height;
@end
在.m文件中也要有相应的写法:
#import<Foundation/Foundation.h>
@implementation Student
@synthesize age;//会在.h文件自动生成一个age成员变量
//上面那句相当于以下代码:
//-----------------------------------------------------------------------------------
//-(void)setAge : (int) newAge{
//age = newAge;
// }
// -(int)age{
// return age;
// }
//-----------------------------------------------------------------------------------
@synthesize no;
@synthesize height;
//也可以把上面三句写成一句代码
//@synthesize age,no,height;
//如果要给自定义的成员变量如:_age赋值,则可写成
//@synthesize age = _age;//表示在.h声明文件中setAge方法要给_age这个成员变量赋值。
//即等价于
//-(void) setAge : (int) newAge{
// _age = newAge;
//}
//-(int) age{
// return _age;
//}
@end
总结:
property会自动生成getter和setter方法的声明。
synthesize会自动生成getter和setter方法的实现。
注意:XCODE4..5以上版本只需在声明文件写@property即可,不用在实现文件写@sythesize语句了,它会自动帮我们生成,同时也会自动生成带下划线前缀的成员变量,如:@property int age;他会自动生成成员变量_age。
5、setter方法释放内存的等效语句写法:
在Student.m文件中:
@implementation Student
#pragam mark setter方法
-(void) setBook : (Book *) book{
if(_book != book){
[_book release];
_book = [book retain];
}
}
//上面这个setter方法可以在Student.h文件中简写成:@property (retain) Book *book;//该retain会自动release旧值,retain新值。
#pragam mark 回收内存
-(void)dealloc{
[_book release];
[_card release];
[super dealloc];
}
}
6、释放内存时可以用self.book = nil;
也可以用[book setBook : nil];
也等价于[_book release];
- ios笔记--OC常用语法归纳小结
- ios笔记--oc语法1
- ios笔记--OC语法基础知识笔记
- IOS开发笔记15-OC基础语法
- IOS开发笔记19-OC特有语法
- ios笔记--oc语法2 (KVC)
- OC语法学习小结
- oc基础语法小结
- OC简单常用知识点归纳
- IOS开发之OC中String常用API小结
- 一 :ios学习笔记 OC入门2 点语法
- 黑马程序员- IOS学习笔记OC核心语法
- 黑马程序员--IOS学习笔记(OC-点语法)
- iOS笔记--oc语法5 (static全局变量与全局变量)
- iOS笔记--oc语法9(NSArray相关知识)
- iOS笔记--oc语法10(动态类型)
- markdown常用语法小结
- pandas常用语法小结
- 开源企业IM-免费企业即时通讯-ENTBOOST V2014.180 Linux版本正式发布
- 视频测试序列下载:YUV文件
- Xcode工程使用CocoaPods管理第三方库新建工程时出现错误
- error in invoking target 'itsping' of makefile
- css层叠次序
- ios笔记--OC常用语法归纳小结
- redis配置文件备忘
- struct tm 和 time_t 时间和日期的使用方法
- EXCEL快捷键大全
- Adaptive Cursor Sharing(ACS)
- Linux 文件 查找命令小结
- 字节转换
- 15 essential mobile game development tools
- sp5v210 添加输入法第二篇