当前位置: 首页 > news >正文

C语言基础回顾与Objective-C核心类型详解

目录

一、C语言基础快速回顾

1. 基本数据类型

2. 运算符

3. 控制流

4. 数组与结构体

二、Objective-C核心类型详解

1. NSString - 字符串处理

2. NSNumber - 基本类型对象化

3. NSArray - 有序集合

4. NSDictionary - 键值对集合

5. nil与NULL的区别

三、动手实践

1. 字符串操作示例

2. 数组操作示例

3. 字典操作示例

四、总结

相关推荐


一、C语言基础快速回顾

1. 基本数据类型

Objective-C作为C的超集,完全支持C语言的所有基本数据类型:

int age = 25;                   // 整型
float height = 1.75f;           // 单精度浮点
double pi = 3.1415926535;       // 双精度浮点
char initial = 'J';             // 字符型
BOOL isStudent = YES;           // Objective-C特有的布尔类型(YES/NO)

2. 运算符

// 算术运算符
int sum = a + b;
int diff = a - b;
int product = a * b;
float quotient = (float)a / b;// 比较运算符
if (a == b) { /* ... */ }
if (a > b) { /* ... */ }// 逻辑运算符
if (condition1 && condition2) { /* ... */ }
if (condition1 || condition2) { /* ... */ }

3. 控制流

// if-else
if (score >= 90) {grade = 'A';
} else if (score >= 80) {grade = 'B';
} else {grade = 'C';
}// for循环
for (int i = 0; i < 10; i++) {printf("%d\n", i);
}// while循环
while (condition) {// 循环体
}// do-while循环
do {// 至少执行一次
} while (condition);

4. 数组与结构体

// 数组
int numbers[5] = {1, 2, 3, 4, 5};
numbers[0] = 10;// 结构体
struct Person {char name[50];int age;
};
struct Person p1 = {"John", 30};

二、Objective-C核心类型详解

1. NSString - 字符串处理

创建字符串:

NSString *greeting = @"Hello, Objective-C!";
NSString *name = [[NSString alloc] initWithFormat:@"%@ %@", firstName, lastName];

常用方法:

// 获取长度
NSUInteger len = [greeting length];// 子字符串
NSString *sub = [greeting substringFromIndex:7]; // "World!"
NSString *subRange = [greeting substringWithRange:NSMakeRange(0, 5)]; // "Hello"// 比较
if ([str1 isEqualToString:str2]) {// 字符串内容相等
}// 大小写转换
NSString *upper = [greeting uppercaseString];
NSString *lower = [greeting lowercaseString];// 查找
NSRange range = [greeting rangeOfString:@"World"];
if (range.location != NSNotFound) {NSLog(@"Found at index %lu", range.location);
}

2. NSNumber - 基本类型对象化

创建NSNumber:

NSNumber *intNum = @42;
NSNumber *floatNum = @3.14f;
NSNumber *doubleNum = @3.1415926535;
NSNumber *boolNum = @YES;

转换回基本类型:

int i = [intNum intValue];
float f = [floatNum floatValue];
BOOL b = [boolNum boolValue];

3. NSArray - 有序集合

不可变数组(NSArray):

NSArray *colors = @[@"Red", @"Green", @"Blue"];
id firstColor = colors[0];  // 或者 [colors objectAtIndex:0]
NSUInteger count = [colors count];// 遍历
for (NSString *color in colors) {NSLog(@"%@", color);
}// 包含检查
if ([colors containsObject:@"Green"]) {NSLog(@"包含绿色");
}

可变数组(NSMutableArray):

NSMutableArray *mutableColors = [NSMutableArray arrayWithArray:colors];
[mutableColors addObject:@"Yellow"];
[mutableColors insertObject:@"Black" atIndex:0];
[mutableColors removeObject:@"Red"];
[mutableColors removeObjectAtIndex:1];

4. NSDictionary - 键值对集合

不可变字典(NSDictionary):

NSDictionary *person = @{@"name": @"John",@"age": @30,@"isStudent": @NO
};NSString *name = person[@"name"];  // 或者 [person objectForKey:@"name"]

可变字典(NSMutableDictionary):

NSMutableDictionary *mutablePerson = [NSMutableDictionary dictionaryWithDictionary:person];
[mutablePerson setObject:@"Doe" forKey:@"lastName"];
[mutablePerson removeObjectForKey:@"isStudent"];

5. nil与NULL的区别

  • NULL是C语言的空指针
  • nil是Objective-C对象的空指针
  • 现代Objective-C中,两者基本可以互换,但约定俗成:
    • 对象用nil
    • 普通指针用NULL
NSString *str = nil;  // Objective-C对象
int *ptr = NULL;      // C指针

三、动手实践

1. 字符串操作示例

        NSString *firstName = @"SCC";NSString *lastName = @"Shuaici";// 字符串拼接NSString *fullName = [NSString stringWithFormat:@"%@==>%@", firstName, lastName];// 字符串分割NSArray *components = [fullName componentsSeparatedByString:@"==>"];// 字符串替换NSString *modified = [fullName stringByReplacingOccurrencesOfString:@"Shuaici" withString:@"Shuaici-SVIP"];

2. 数组操作示例

// 创建数组
NSArray *originalArray = @[@1, @2, @3, @4, @5];// 映射
NSMutableArray *squaredArray = [NSMutableArray array];
for (NSNumber *num in originalArray) {[squaredArray addObject:@([num intValue] * [num intValue])];
}// 过滤
NSPredicate *evenPredicate = [NSPredicate predicateWithFormat:@"modulus:by:(SELF, 2) == 0"];
NSArray *evenNumbers = [originalArray filteredArrayUsingPredicate:evenPredicate];// 排序
NSArray *sorted = [originalArray sortedArrayUsingSelector:@selector(compare:)];

3. 字典操作示例

// 创建字典
NSMutableDictionary *employee = [NSMutableDictionary dictionary];
[employee setObject:@"Shuaici" forKey:@"name"];
[employee setObject:@30 forKey:@"age"];
[employee setObject:@"Developer" forKey:@"position"];// 更新值
[employee setObject:@31 forKey:@"age"];// 遍历
for (NSString *key in employee) {NSLog(@"%@: %@", key, employee[key]);
}// 字典转JSON
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:employee options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

四、总结

        Objective-C在C语言基础上引入了丰富的面向对象特性,其中核心类型如NSString、NSNumber、NSArray和NSDictionary是日常开发中最常用的类。理解这些类型的特点和用法是掌握Objective-C开发的基础。不可变类型(NSString, NSArray, NSDictionary)和它们的可变版本(NSMutableString, NSMutableArray, NSMutableDictionary)之间的区别尤其重要,这关系到代码的安全性和性能。

相关推荐

C语言基础精讲-CSDN博客文章浏览阅读10w+次,点赞413次,收藏2.1k次。C语言是当代人学习及生活中的必备基础知识,应用十分广泛,下面为大家带来C语言基础知识梳理总结,C语言零基础入门绝对不是天方夜谭!_c语言基础知识 https://shuaici.blog.csdn.net/article/details/60570837

为何要学习Objective-C?从环境搭建开始-CSDN博客文章浏览阅读514次,点赞10次,收藏10次。在Objective-C开发中,你会频繁遇到以"NS"开头的类名和函数名,比如NSLog、NSString、NSArray等。这个"NS"前缀其实有着重要的历史渊源和技术含义。 https://shuaici.blog.csdn.net/article/details/148535298

http://www.lqws.cn/news/514027.html

相关文章:

  • QT 学习笔记摘要(三)
  • 每日AI资讯速递 | 2025-06-25
  • TDengine 的 CASE WHEN 语法技术详细
  • 磐维数据库PanWeiDB V2.0-S3.1.1_B01集中式一主二备安装
  • linux安装docker
  • Android14音频子系统-ASoC-ALSA之DAPM电源管理子系统
  • ISO/IEC 27001:2022 資訊安全管理系統 Information Security Management System , ISMS
  • elementui修改radio字体的颜色和圆圈的样式
  • centos7网络不可达connect: network is unreachable
  • 【JVS更新日志】物联网、智能排产APS、企业计划、规则引擎6.25更新说明!
  • 华为云Flexus+DeepSeek征文|基于Dify构建智能情感分析Agent全流程
  • MiniMax-M1混合MoE大语言模型(本地运行和私有化搭建)
  • 【零基础学AI】第3讲:Git版本控制基础
  • Java项目RestfulAPI设计最佳实践
  • 深入剖析:Spring Boot系统开发的高效之道
  • T-BOX 革新:ASR1606 LTE Cat.1 联合 SD NAND MKDV1GIL-AST 的优势剖析
  • 签名组件:uniapp 签名组件开发,兼容小程序、H5、App等 电子签名
  • Python DuckDB 详解:轻量级分析型数据库的革新实践
  • 学习昇腾开发的第8天
  • 通用 Excel 导出功能设计与实现:动态列选择与灵活配置
  • 鸿蒙ArkUI---基础组件Tabs(Tabbar)
  • ASR1606 LTE Cat.1 与 MK SD NAND–––T-BOX 智能基座的通信存储双擎
  • x86-64安装编译Apollo 9.0 aarch64版本
  • ZArchiver×亚矩云手机:云端文件管理的“超维解压”革命
  • B树和B+树的区别
  • SpringBoot项目快速开发框架JeecgBoot——数据访问!
  • 从零开始的云计算生活——第二十三天,稍作休息,Tomcat
  • pycharm基础操作备忘记录
  • 国芯思辰|同步降压转换器CN2020A替换LMR33620应用于分布式电源系统
  • Jenkins X + AI:重塑云原生时代的持续交付范式