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
···
相关推荐
opentogether26 分钟前
PODS_ROOT、BUILT_PRODUCTS_DIR和SRCROOT有什么区别
ios
Spiffo_Sir3 小时前
【Spiffo】光速项目:LVGL v9框架下的MIPI简易相机_Part2
linux·c语言·数码相机
xueyinan3 小时前
小刚说C语言刷题——第21讲 一维数组
c语言
90后的晨仔4 小时前
Socket 与 WebSocket 的区别是啥?
ios
ん贤4 小时前
蓝桥杯考前复盘
c语言·c++·算法·职场和发展·蓝桥杯
khazix1015 小时前
【C语言】--- 文件操作
c语言·开发语言
理智的灰太狼5 小时前
题目 2701: 蓝桥杯2022年第十三届决赛真题-取模(C/C++/Java组)
c语言·c++·蓝桥杯
林晨月5 小时前
SwiftUI 国际化
ios
Funny Valentine-js6 小时前
swift菜鸟教程1-5(语法,变量,类型,常量,字面量)
开发语言·ios·swift
暗影~行星8 小时前
C语言,原码、补码、反码
c语言·开发语言