OC学习那些事:第一个OC类

一、创建一个新的OC类: 

1.点击File->New File,打开Choose a template for your new file窗口,选择Objective-C class,点击Next按钮 

Image

2.Choose options for your new file窗口,在Class中输入Student类名,Subclass of中输入子类NSObject父类名称。点击Next按钮 

Image

3.选择类所在的存储路径。点击按钮 

Image

4.在项目中生成了Student.h和Student.m文件 

Image

.h类声明文件,用户声明变量、函数(方法 

.m类实现文件,用户实现.h中的函数(方法  

5.查看Student.h类文件,学习类的声明语法。 

 

#import <Foundation/Foundation.h> 
 
//@interface:代表声明一个类 
//::代表继承 
@interface Student : NSObject 
//{}:成员变量定义在大括号中,推荐使用_age 
{ 
    int _age; 
} 
//+/-:代表动态和静态方法,所有的方法都是公共的 
-(int)getAge; 
-(void)setAge:(int)age; 
@end  

6.点击Student.m类实现文件,学习类的实现语法。 

#import "Student.h" 
//@implementation:代表实现一个类 
@implementation Student 
//get方法,建议使用age方法名 
-(int)age 
{ 
    return _age; 
} 
//set方法,建议使用setAge:(int) newAge方法名。 
-(void)setAge:(int)age 
{ 
    _age = age; 
} 
@end 

7.点击main.m方法,创建一个OC类的对象。 

#import <Foundation/Foundation.h> 
#import "Student.h" 
int main(int argc, const char * argv[]) 
{ 
    @autoreleasepool { 
        //创建一个Student对象 
        //1.调用静态方法alloc类分配内存 
        Student * stu = [Student alloc]; 
        //2.调用一个静态的init进行初始化 
        stu = [stu init]; 
    } 
    return 0; 
} 


 

原文地址:https://www.cnblogs.com/snake-hand/p/3190329.html