OC基础语法

头文件

 1 @interface Student : NSObject{
 2     int age;
 3     int height;
 4 }//成员变量的声明区间,成员变量必须在此声明
 5 
 6 - (int)age;//本来是getAge,但是OC的习惯是用变量来命名get方法
 7 - (void)setAge:(int)newAge;
 8 //多形参的函数写法比较特别
 9 - (void)setAge:(int)newAge andHeight:(int)newHeight;
10 @end//类的结束标记,必须写

对应的m文件为

 1 #import "Student.h"
 2 @implementation Student
 3 
 4 - (int)age{
 5     return age;
 6 }
 7 - (void)setAge:(int)newAge{
 8     age = newAge;
 9 }
10 - (void)setAge:(int)newAge andHeight:(int)newHeight{
11     age = newAge;
12     height = newHeight;
13 }
14 @end

对象的创建和方法调用

//OC创建对象分2步,先调用静态无参函数alloc申请内存,在调用静态无参函数init初始化
//1. Student *stu = [Student alloc];//仅仅为对象分陪内存空间
//2. stu = [stu init];//真正创建对象
//以上2步一般简写为:
Student *stu = [[Student alloc] init]; 
//设置
[stu setAge:100];
[stu setAge:100 andHeight:50];
//获取
NSLog(@"age is %i",[stu age]);
[stu release];//对象使用完毕要释放内存

对象的构造方法

 1 @interface Student{
 2     int _age;//标准写法
 3     int _no;
 4 }
 5 - (void)setAge:(int)age;
 6 - (int)age;
 7 - (void)setNo:(int)no;
 8 - (int)no;
 9 //构造方法
10 - (id)initWithAge:(int)age andNo:(int)no;
11 @end

对应的m文件:

 1 #include "Student.h"
 2 @implementation Student
 3 
 4 - (int)age{
 5     return _age;
 6 }
 7 - (void)setAge:(int)age{
 8     _age = age;
 9 }
10 //...
11 //实现构造方法
12 - (id)initWithAge:(int)age andNo:(int)no{
13     //以下写法不严谨
14     //self = [super init];
15     //_age = age;
16     //_no = no;
17     if(self=[super init]){
18         _age = age;
19         _no = no;
20     }
21     return self;
22 }
23 @end
原文地址:https://www.cnblogs.com/ljwiOS/p/4818794.html