概述

  1. Objective-C 最大的特色是承自Smalltalk的消息传递模型(message passing).在 Objective-C 中,调用方法视为对对象发送消息,所有方法都被视为对消息的回应.所有消息处理直到运行时才会动态决定,并交由类自行决定如何处理收到的消息.
  2. 一个类不保证一定会回应收到的消息,如果类别收到了一个无法处理的消息,程序只会抛出异常,不会出错或崩溃.
calculator.h
calculator.m
main.m
#ifndef Calculator_h
#define Calculator_h

#import <Foundation/Foundation.h>

// 类的声明以 @interface 开头,以 @end 结尾.
@interface Calculator : NSObject
{
    // 变量声明
    @public
    float price;   // 成员变量
    string clolor;        // 成员变量
}
// 方法声明
// 对象方法的方法类型用 "-" 表示.
// 类方法的方法类型用 "+" 表示.
-(double)pi;
-(double)square:(double)number;
-(double)sumOfNum1:(double)num1 :(double)num2;
-(void)show;
@end
#endif /* Calculator_h */
#import "Calculator.h"

@implementation Calculator 
-(double)pi {
    return 3.14;
}

-(double)square:(double)number {
    return number * number;
}

-(double)sumOfNum1:(double)num1 :(double)num2 {
    return num1 + num2;
}

-(void) show {
    NSLog(@"%f元, %s的计算器", price,color);
}
@end
#import "Calculator.h"

int main(int argc, const char * argv[]) {
    // 自动释放池
    @autoreleasepool {
        // 创建对象
        Calculator *c = [[Calculator alloc]init];
        // 消息机制: [消息接收者 消息名称]
        double a1 = [c pi];
        NSLog(@"pi的值为%f",a1);
        // 消息机制: [消息接收者 消息名称 : 消息参数]
        double a2 = [c square:2.5];
        NSLog(@"2.5的平方和为%f",a2);
        double a3 = [c sumOfNum1:2.5:3.6];
        NSLog(@"2.5与3.6两个和为%f",a3);
        c->price = 100.0;
        c->color = "green";
        [c show];
    }
    return 0;
}
+ 创建对象的两种方式
  1. 类名* 实例对象 = [类名 new];
  2. 类名* 实例对象 = [[类名 alloc] init];
+ 消息机制
  1. 消息接收者可以为对象名,也可以是类名.
  2. 一般来说,给实例对象发送消息, 调用对象方法.给类发送消息, 调用类方法.
+ 自动释放池
  1. @autoreleasepool 用于声明一个自动释放池,后面的花括号是其作用域,当程序执行到括号末尾的时候,自动释放池被销毁,其作用域里面的每一个对象都会收到 release 消息.

set 与 get 方法

student.h
student.m
main.m
#ifndef Student_h
#define Student_h

#import <Foundation/Foundation.h>
@interface Student : NSObject
{
    float _weight;
    int _age;
}
-(void)eat;
-(void)setWidget:(float)weight;
-(float)weight;
-(void)setAge:(int)age;
-(int)age;
@end
#endif /* Student_h */
#import "student.h"
@implementation Student
-(void)eat
{
    NSLog(@"年龄为%d岁的学生体重为%f公斤", _age, _weight);
}
-(void)setWeight:(float)weight
{
    if (weight >= 200 || weight <= 0) {
        NSLog(@"体重不合法");
    }
}
-(float)weight
{
    return _weight
}
-(void)setAge:(int)age
{
    if (age <= 0) {
        NSLog(@"年龄不合法");
    }
}
-(int)age
{
    return _age;
}
@end
#import "student.h"
int main(int argc, const char* argv[]) {
    Student *stu = [[Student alloc] init];
    [stu setAge:-10];
    [stu setWeight:1000];
    [stu eat];
    return 0;
}

参考链接

  1. objective-c基础
  2. objective-c