目录
一、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)之间的区别尤其重要,这关系到代码的安全性和性能。