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
···
相关推荐
智者知已应修善业3 小时前
【51单片机普通延时奇偶灯切换】2023-4-4
c语言·经验分享·笔记·嵌入式硬件·51单片机
晚风(●•σ )3 小时前
C++语言程序设计——11 C语言风格输入/输出函数
c语言·开发语言·c++
X***48964 小时前
C源代码生成器
c语言·开发语言
合作小小程序员小小店6 小时前
桌面安全开发,桌面二进制%恶意行为拦截查杀%系统安全开发3.0,基于c/c++语言,mfc,win32,ring3,dll,hook,inject,无数据库
c语言·开发语言·c++·安全·系统安全
2501_915106328 小时前
iOS App 测试工具全景分析,构建从开发调试到线上监控的多阶段工具链体系
android·测试工具·ios·小程序·uni-app·iphone·webview
oioihoii8 小时前
C++语言演进之路:从“C with Classes”到现代编程基石
java·c语言·c++
Digitally11 小时前
如何通过蓝牙将联系人从 iPhone 传输到 Android
android·ios·iphone
90后的晨仔11 小时前
2025年11月27日年解决隐私清单导致审核总是提示二进制无效的问题
ios
历程里程碑11 小时前
各种排序法大全
c语言·数据结构·笔记·算法·排序算法
树在风中摇曳11 小时前
带哨兵位的双向循环链表详解(含 C 代码)+ LeetCode138 深度解析 + 顺序表 vs 链表缓存机制对比(图解 CPU 层级)
c语言·链表·缓存