总目录 iOS开发笔记目录 从一无所知到入门

文章目录

Intro截图自定义类型的`@interface`部分和`@implementation`部分main方法中的类型调用部分

Demo测试代码输出

Intro

Objective-C,具有面向对象特性的C。 但其实,它的面向对象和其他高级语言相比,还是有很大的差异【OC的面向对象是来自于另一种较为古早的编程语言smalltalk的消息传递】。 每次点到一些iOS项目里都能看到那些奇怪的我不懂的语法,所以如果自己真心实意想开发iOS程序,Objective- C的面向对象部分的语法还是要仔细过一下。

以下代码包含:

如何自定义一个新类型? @interface 和 @implementation 两部分。@interface 的基本组成(可以有,不是必须有): 成员属性、成员方法/对象方法的声明、类方法的声明。@implementation 的基本组成: 类的实现。如何声明并实例化一个对象?如何读写对象的某个成员属性值?通过箭头符号。无参数、无返回值的方法的声明和调用。含有多个参数的方法的声明写法和调用方法。对象方法和类方法的调用区别。

截图

自定义类型的@interface部分和@implementation部分

main方法中的类型调用部分

Demo

测试代码

//

// main.m

// 类和对象的基本使用

//

// Created by wuyujin1997 on 2023/2/23.

//

#import

// 类型定义(包含成员属性、方法定义的接口)

@interface Person : NSObject {

@public

NSString* name;

int age;

}

- (void) sayHi; // 无参数、无返回值的方法声明。

- (NSString*) toString; // 无参数、有返回值的方法声明。

- (int) sumWithNumA:(int)a numB:(int)b; // 有返回值、且有多个参数(推荐写法)。

- (int) sumFourNum:(int)a :(int)b :(int)c numD:(int)d; // 多个参数的情况下,可以省略部分参数的名称(不推荐)。

// 减号-开头表示是成员方法,由对象调用。

// 加号+开头表示是类方法,可以直接由类名调用。

+ (Person*) createPersonWithName:(NSString*)name age:(int)age;

@end

// 类的实现(包含方法的具体实现)

@implementation Person

- (void) sayHi {

NSLog(@"hello wuyujin1997");

}

- (NSString*) toString {

// 将多个参数拼接、格式化为一个字符串对象

NSString* resultStr = [NSString stringWithFormat:@"Name:%@ Age:%d", name, age];

return resultStr;

}

- (int) sumWithNumA: (int)a numB: (int)b {

return a + b;

}

- (int) sumFourNum:(int)a :(int)b :(int)c numD:(int)d {

return a + b + c + d;

}

+ (Person*) createPersonWithName:(NSString*)name age:(int)age {

Person* person = [Person new];

person->name = name;

person->age = age;

return person;

}

@end

int main(int argc, const char * argv[]) {

// 实例化一个对象并赋值

// Person* person = [[Person alloc] init];

Person* person = [Person new];

// 对象调用方法,准确的说:【向对象传递消息】。

[person sayHi];

// 对象指针如何调用成员?使用【箭头符号】。

person->name = @"wuyujin1997"; // 如何写一个成员属性?

NSLog(@"name: %@", person->name); // 如何读一个成员属性?

person->age = 26;

// 调用一个有返回值的成员方法

NSString* personInfo = [person toString];

NSLog(personInfo);

// 调用一个有返回值、且有多个参数的方法。

int resultValue = [person sumWithNumA:10 numB:22];

NSLog(@"sum result: %d", resultValue);

// 调用某个含多个参数的函数(该只有部分参数有参数名、部分参数没有参数名)

int sumResult = [person sumFourNum:2 :4 :6 numD:8];

NSLog(@"sum result: %d", sumResult);

// 类方法调用测试

Person* p = [Person createPersonWithName:@"张三" age:22];

NSLog([p toString]);

return 0;

}

输出

2023-02-23 22:38:17.083168+0800 类和对象的基本使用[9370:284964] hello wuyujin1997

2023-02-23 22:38:17.083366+0800 类和对象的基本使用[9370:284964] name: wuyujin1997

2023-02-23 22:38:17.083407+0800 类和对象的基本使用[9370:284964] Name:wuyujin1997 Age:26

2023-02-23 22:38:17.083422+0800 类和对象的基本使用[9370:284964] sum result: 32

2023-02-23 22:38:17.083433+0800 类和对象的基本使用[9370:284964] sum result: 20

2023-02-23 22:38:17.083452+0800 类和对象的基本使用[9370:284964] Name:张三 Age:22

Program ended with exit code: 0

推荐链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: