第03天OC语言(06):self关键字基本概念

  • 不要等到明天,明天太遥远,今天就行动。

#####须读:看完该文章你能做什么?

#####学习前:你必须会什么?(在这里我已经默认你具备C语言的基础了)

什么是类


#####一、本章笔记

 self不能离开类,离开类没有任何意义

#####二、code ######main.m

#pragma mark 06-self关键字基本概念
#pragma mark - 代码
#import <Foundation/Foundation.h>
#pragma mark 类
#import "IPhone.h"
#pragma mark - main函数
int main(int argc, const char * argv[])
{
    [IPhone carameWithFlahlightStatus:kFlahlightStatusClose];
    return 0;
}
>>>Iphone
.h

.m
#import "IPhone.h"

@implementation IPhone
/*
 类方法中 可以 直接调用类方法
 类方法中 不可以 直接调用对象方法
 类方法中 不能访问成员变量
 */
+ (void)carameWithFlahlightStatus:(FlahlightStatus)status
{
    if (status == kFlahlightStatusOpen)
    {
//        [IPhone openFlashlight];
        // self == IPhone
        [self openFlashlight];
    }
    else
    {
//        [IPhone closeFlashlight];
        [self closeFlashlight];
    }
    
    NSLog(@"拍照");
}

// 打开闪光灯
+ (void)openFlashlight
{
    NSLog(@"打开闪光灯");

}
// 关闭闪光灯
+ (void)closeFlashlight
{
    NSLog(@"关闭闪光灯");

}

@end
>>>06-self关键字2
>>>Main.m
#pragma mark 06-self关键字2
#pragma mark 概念

#pragma mark - 代码
#import <Foundation/Foundation.h>
#pragma mark 类
#import "IPhone.h"
#pragma mark - main函数
int main(int argc, const char * argv[])
{
    IPhone *p = [IPhone new];
    NSLog(@"p = %p",p);
    [p carameWithFlahlightStatus:kFlahlightStatusOpen];
    return 0;
}

######Iphone

>>>.h
#import <Foundation/Foundation.h>

typedef enum
{
    kFlahlightStatusOpen,
    kFlahlightStatusClose
}FlahlightStatus;

@interface IPhone : NSObject
{
    int _cpu;
}
//根据闪光灯的状态拍照
- (void)carameWithFlahlightStatus:(FlahlightStatus)status;

// 打开闪光灯
- (void)openFlashlight;
// 关闭闪光灯
- (void)closeFlashlight;

@end
>>>.m
#import "IPhone.h"

@implementation IPhone
/*
 如果self 在对象方法中,那么 self就代表调用 当前对象方法的那个对象
 如果self 在类方法中 , 那么 self 就代表 调用 当前类方法的那个类
 
 总结 : 
 我们只用 关注 self在那个方法中, 如果在类方法 那么就代表当前类, 如果在对象方法 那么就代表当前调用该方法的对象
 */
- (void)carameWithFlahlightStatus:(FlahlightStatus)status
{
    if (status == kFlahlightStatusOpen)
    {
        // 其实 self 不仅仅可以调用我们的类方法 还可以调用对象方法
        // self == 对象 == p
        NSLog(@"self = %p",self);
        [self openFlashlight];
    }
    else
    {
        [self closeFlashlight];
    }
    
    NSLog(@"拍照");
}

// 打开闪光灯
- (void)openFlashlight
{
    NSLog(@"打开闪光灯");

}
// 关闭闪光灯
- (void)closeFlashlight
{
    NSLog(@"关闭闪光灯");

}

@end

转载于:https://my.oschina.net/u/3561184/blog/1358990

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值