- 不要等到明天,明天太遥远,今天就行动。
须读:看完该文章你能做什么?
学习前:你必须会什么?(在这里我已经默认你具备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