0%

Objective-C基础入门(类)

分离Interface和Implementation文件

section 文件后缀 import
类申明(@interface section) class.h import <Foundation/Foundation.h>
类实施(@implementation section) class.m import “class.h” (引入local file)
主程序(main program section) main.m import “class.h” (只需要@interface就够了)

可以把 @interface 看作 public information
可以把@implementation 看作 private information

合成访问方法

自动生成setter和getter方法
在interface中申明:@property + 实例变量名
在implementation中自动合成:@synthesize + 实例变量名 (现在不需要再申明实例变量了)
⚠️ 若在implementation中不使用@synthesize,系统会自动生成带有_的实例变量,如_numerator

使用点操作符访问属性

之前学习过访问实例的某个方法如下:
[instance property]

现在也可以用点操作符表示
instance.property

原本的[instance setProperty: value] 等价于 instance.property = value

多个参数的方法

@interface

1
-(void) setTo: (int) n over: (int) d;

@implementation

1
2
3
4
-(void) setTo: (int) n over: (int) d {
numerator = n;
denominator = d;
}

program section

1
[aFraction setTo: 100 over: 200]

无参数名方法:外部参数名都可省略,如:
- (int) set: (int) n: (int) d;
[aFraction set:1 :3]
但不推荐,因为这样可读性很差

static 关键字

static关键字声明的变量必须放在implementation外面,或者方法中,如果不为它赋值默认为0,它只在程序开机初始化一次,之后会储存维护一个值

声明后的static静态变量在其他类中是不能通过类名直接访问的,它的作用域只能是在声明的这个.m文件中

举例:

1
2
3
4
5
6
7
8
9
@implementation MyClass

+ (void)addCount {
static NSInteger count = 100;
count ++;
NSLog(@"static value is %ld", (long)count);
}

@end

其输出结果为:

1
2
3
4
5
2015-12-07 17:41:33.397 StaticDemo[80984:2870442] static value is 101
2015-12-07 17:41:33.398 StaticDemo[80984:2870442] static value is 102
2015-12-07 17:41:33.398 StaticDemo[80984:2870442] static value is 103
2015-12-07 17:41:33.398 StaticDemo[80984:2870442] static value is 104
2015-12-07 17:41:33.398 StaticDemo[80984:2870442] static value is 105

count的值是会变化的,而不是一直输出101

self 关键字

本章中未详细介绍,自行百度了相关学习内容:
https://www.jianshu.com/p/1adc99ab62c2