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
···
相关推荐
tangbin58308514 小时前
iOS Swift 可选值(Optional)详解
前端·ios
yyy(十一月限定版)14 小时前
c语言——二叉树
c语言·开发语言·数据结构
IT方大同15 小时前
循环结构的功能
c语言·数据结构·算法
黎雁·泠崖15 小时前
吃透指针通用用法:回调函数与 qsort 的使用和模拟
c语言·开发语言
脏脏a15 小时前
聊聊 C 里的进制转换、移位操作与算术转换
c语言·开发语言·移位操作符
xie_pin_an15 小时前
深入解析 C 语言排序算法:从快排优化到外排序实现
c语言·算法·排序算法
inputA16 小时前
【rt-thread】点灯实验和按键输入实验
c语言·笔记·学习·实时操作系统
EXtreme3516 小时前
【数据结构】二叉树进阶:层序遍历不仅是按层打印,更是形态判定的利器!
c语言·数据结构·二叉树·bfs·广度优先搜索·算法思维·面试必考
子木鑫16 小时前
【练习】循环
c语言
shanks6617 小时前
FFmpeg 入门指南:多媒体处理的瑞士军刀
c语言·ffmpeg