类与对象

  1. 在OC中变量是有默认值的,可以通过重写init函数给予变量赋初值,init的返回类型是对象。
  2. 类是抽象的,它泛指某一堆事物,是一组具有相同特征属性和行为的对象集合。
  3. 对象(实例)是类的具体实现,对象是一个个体。对象在内存中,对象间没有任何联系。
  4. 类由@interface和@implement两部分组成看,分别在xx.h和xx.m文件上。前者是对成员变量(实例变量、全局变量)的声明及函数原型的声明。后者是方法实现。
  5. 主函数中使用类的步骤:导入类的头文件、初始化对象、实例变量赋值访问和方法使用(只能调用类里声明过的方法)。
  6. +类方法里头不能直接访问调用实例方法和变量,若要则通过创建对象。类可以直接调用类方法。
  7. 便利初始化函数(实例方法)和便利构造器(类方法):作用初始化成员变量,好处通过创建对象就可以给多个变量赋值,比init方法的固定值灵活的多。

  类的定义

(1)Student.h中类的声明

@interface Student : NSObject
{
    @public
    //全局变量(成员变量)
    int _age;
    char *_name;
    int _id;
}
//声明方法
-(void) learn;
-(void) eat;
@end

(2)Student.m中方法实现

#import "Student.h"

@implementation Student
-(void) learn
{
    printf("%s is learning
",_name);
}

-(void) eat
{
    printf("%s is eating
",_name);
}
@end

AppDelegate.m

#import "AppDelegate.h"
#import "Student.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    
    //声明一个对象
    Student *stu1 = nil;
    //申请内存并初始化(实例化对象)
    stu1 = [Student alloc];
    stu1 = [stu1 init];
    
    //Student *stu1 = [[Student alloc]init];//嵌套式初始化
    
    //赋值
    stu1->_age = 27;
    stu1->_name = "jobs";
    
    //调用方法
    [stu1 learn];
    [stu1 eat];
    

    [self.window makeKeyAndVisible];
    return YES;
}
原文地址:https://www.cnblogs.com/huen/p/3506388.html