iOS object-c 常用API汇总

前言

本文为入门iOS开发,object-c语法汇总。用于日常查阅。

苹果开发者平台Objective-C文档中文翻译版
Objective-C教程
Objective-C入门教程

文件类型

扩展名 内容类型
.h 头文件。头文件包含类,类型,函数和常数的声明。
.m 源代码文件。这是典型的源代码文件扩展名,可以包含Objective-C和C代码。
.mm 源代码文件。带有这种扩展名的源代码文件,除了可以包含Objective-C和C代码以外还可以包含C++代码。仅在你的Objective-C代码中确实需要使用C++类或者特性的时候才用这种护展名。

简单示例

  • 主要是方法的声明和调用,NSLog的使用等等。
  • @property关键字声明的属性替代了成员变量age的声明,以及set和get方法的声明
  • 构造函数写法赋值self
  • 析构函数dealloc
oc 复制代码
// Person.h
#ifndef Person_h
#define Person_h

@interface Person : NSObject
@property NSString *name;
@property BOOL sex;
@property int age;

-(id)initWithNameAge: (NSString*)name :(int)age;
-(void) print;
-(void) setNameAge:(NSString*)name age:(int) age;
-(int) compare:(Person*) other;
@end

#endif /* Person_h */

//Person.m///
#import <Foundation/Foundation.h>
#import "Person.h"

@implementation Person
@implementation Person
- (id)init { // 默认构造函数
    self = [super init];
    if (self != nil) {
        self.name = @"none";
        self.age = -1;
    }
    return self;
}

- (id)initWithNameAge:(NSString *)name :(int)age{  // 参数构造函数
    self = [super init];
    if (self != nil) {
        self.name = name;
        self.age = age;
    }
    return self;
}

-(void) print{
    NSLog(@"Person: %@, %d", self.name, self.age);
}

- (NSString *)description{  // 复写toString函数
    return [NSString stringWithFormat:@"Person: %@, %d", self.name, self.age];
}

-(void)setNameAge:(NSString *)name age:(int)age{
    self.name = name;
    self.age = age;
}

-(int)compare:(Person *)other{
    return self.age > other.age;
}

- (void)dealloc {  // 类似析构函数
    NSLog(@"@person %@ dealloc", self.name);
}
@end

//test.m
- (void)testExample {
    Person* p = [Person new];
    [p print];
    [p setNameAge:@"Alex" age:20];
    [p print];
    
    Person *p1= [[Person alloc]init];
    p1.age = 10; // 点语法,相当于[p1 setAge:10];
    int older = [p1 compare:p];
    NSLog(@"older: %d, %@", older, p);
    
    Person *p2 = [[Person alloc] initWithNameAge:@"Tom" :30];
    NSLog(@"%@", p2);
}

分类

分类可以在不创建子类的情况下,对原有类进行扩展

分类的格式与类定义的格式相似,也是分为@interface和@implementation两部分,

调用的时候正常调用,只是类的一个分类。

oc 复制代码
#import "类名.h"
@interface 类名(分类名称)
  方法声明
@end


#import "类名+分类名.h"
@implementation 类名(分类名称)
    方法实现
@end
···
相关推荐
铅笔小新z1 天前
【C语言】操作符
c语言
by209991 天前
从 malloc/free 到 new/delete:真正理解 C++ 中的内存管理与对象生命周期
c语言·c++·经验分享·动态内存管理
额额额对了1 天前
SPI通信
linux·c语言·汇编·单片机·嵌入式硬件·arm
Logic1011 天前
C语言/数据结构位运算题解:异或XOR找出书柜中编号只出现一次的那一层——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
传奇开心果编程1 天前
【SwiftUI入门练中学】第7课 动画与手势:让界面更灵动
学习·macos·ui·ios·swiftui·swift
Logic1011 天前
C语言/数据结构位运算题解:异或XOR找出星球探险中的“独特能量石“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
Escalating_xu1 天前
【C 语言】深入理解指针(3):字符指针、数组指针、二维数组传参、函数指针与转移表
java·c语言·开发语言
垆边人似月.1 天前
华为机考题:最小代价爬楼梯
c语言·c++
知潮网1 天前
发售刚十天,9999 元的 iPhone 18 Pro 解锁就重启
ios·iphone
垆边人似月.1 天前
华为机考题:二叉树的最大路径和
c语言·c++