Objective-C

93 阅读2分钟

1. 文件结构

  • 头文件(.h :声明类的接口、属性和方法。
  • 实现文件(.m :实现类的具体功能。
// Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property NSString *name;
- (void)sayHello;
@end

// Person.m
#import "Person.h"
@implementation Person
- (void)sayHello {
    NSLog(@"Hello, my name is %@.", self.name);
}
@end

2. 导入文件

  • 使用 #import 导入头文件,避免重复包含。
#import <Foundation/Foundation.h>
#import "Person.h"

3. 数据类型

  • 基本类型intfloatdoublecharBOOL(YES/NO)。
  • 对象类型NSStringNSArrayNSDictionary 等。
int age = 25;
float height = 5.9;
NSString *name = @"Lihongjun";
BOOL isStudent = YES;

4. 对象创建和方法调用

  • 创建对象使用 allocinit
  • 调用方法使用方括号 [ ]
Person *person = [[Person alloc] init];
[person setName:@"Lihongjun"];
[person sayHello];

5. 属性(Properties)

  • 声明属性使用 @property

  • 属性修饰符:

    • nonatomic:非线程安全。
    • atomic:线程安全(默认)。
    • strong:强引用(默认)。
    • weak:弱引用。
    • copy:拷贝值。
    • readonly:只读。
@property (nonatomic, strong) NSString *name;

6. 方法

  • 实例方法以 - 开头,类方法以 + 开头。
  • 方法声明和实现:
// 声明
- (void)sayHello;
+ (void)classMethod;

// 实现
- (void)sayHello {
    NSLog(@"Hello, world!");
}
+ (void)classMethod {
    NSLog(@"This is a class method.");
}

7. 条件和循环

  • 条件语句:
if (age > 18) {
    NSLog(@"Adult");
} else {
    NSLog(@"Minor");
}
  • 循环语句:
for (int i = 0; i < 5; i++) {
    NSLog(@"%d", i);
}
NSArray *names = @[@"Alice", @"Bob", @"Charlie"];
for (NSString *name in names) {
    NSLog(@"%@", name);
}

8. 类与继承

  • Objective-C 中所有类的根类是 NSObject
  • 使用 @interface 声明类,@implementation 实现类。
  • 子类使用 : 父类名
@interface Student : Person
@property NSString *studentID;
@end

9. 内存管理

  • 使用 ARC(Automatic Reference Counting)。

  • 若手动管理:

    • retain:增加引用计数。
    • release:减少引用计数。
    • autorelease:延迟释放。

10. 协议(Protocols)

  • 类似于接口,使用 @protocol 声明。
@protocol MyProtocol <NSObject>
- (void)doSomething;
@end

11. 分类(Categories)

  • 用于扩展现有类的方法。
@interface NSString (ReverseString)
- (NSString *)reverseString;
@end

@implementation NSString (ReverseString)
- (NSString *)reverseString {
    NSMutableString *reversed = [NSMutableString string];
    for (NSInteger i = self.length - 1; i >= 0; i--) {
        [reversed appendFormat:@"%C", [self characterAtIndex:i]];
    }
    return reversed;
}
@end

12. 块(Blocks)

  • 相当于匿名函数或闭包。
void (^simpleBlock)(void) = ^{
    NSLog(@"This is a block.");
};
simpleBlock();

int (^add)(int, int) = ^(int a, int b) {
    return a + b;
};
NSLog(@"%d", add(5, 3));

13. 错误处理

  • 使用 @try@catch@finally
@try {
    NSArray *array = @[];
    NSLog(@"%@", array[1]); // 越界
} @catch (NSException *exception) {
    NSLog(@"Exception: %@", exception.reason);
} @finally {
    NSLog(@"Cleanup code");
}