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
···
相关推荐
键盘敲没电7 小时前
【IOS】GCD学习
学习·ios·objective-c·xcode
SY.ZHOU7 小时前
Significant Location Change
macos·ios·cocoa
hjyowl8 小时前
题解:AT_abc407_c [ABC407C] Security 2
c语言·开发语言·算法
old_power9 小时前
UCRT 和 MSVC 的区别(Windows 平台上 C/C++ 开发相关)
c语言·c++·windows
@老蝴10 小时前
C语言 — 编译和链接
c语言·开发语言
LunaGeeking11 小时前
三分算法与DeepSeek辅助证明是单峰函数
c语言·c++·算法·编程·信奥赛·ai辅助学习·三分
whoarethenext14 小时前
使用 C/C++ 和 OpenCV 实现滑动条控制图像旋转
c语言·c++·opencv
吴Wu涛涛涛涛涛Tao14 小时前
深入理解 Swift Codable:从基础到进阶
ios
陳麦冬16 小时前
深入理解指针(二)
c语言·学习
景彡先生20 小时前
C++中的变量
c语言