首先申明下,本文为笔者学习《Objective-C 基础教程》的笔记,并加入笔者自己的理解和归纳总结。

1. 字符串类

NSString是不可变的字符串,而NSMutableString是可变的,可以对它进行各种操作。
NSMutableStringNSString的子类,可以调用NSString的方法。

1.1 NSString类

@符号和双引号可以直接定义一个字符串。
stringWithFormat:方法可以输出一个字符串。加号(+)表明是一个类方法。

+ (NSString *)stringWithFormat:(NSString *)format, ...;

length返回字符串中的字符个数。

- (NSInteger)length;

isEqualToString:比较两个字符串,返回BOOL值(YESNO)。

- (BOOL)isEqualToString:(NSString *)aString;

compare:比较字符串,返回枚举类型NSComparisonResult(NSOrderedAscendingNSOrderedSameNSOrderedDescending)。

- (NSComparisonResult)compare:(NSString *)string;

compare: options:可以不区分大小写。options参数是一个掩位码。NSCaseInsensitiveSearch,不区分大小写。NSLiteralSearch,进行完全比较,区分大小写。NSNumericSearch,比较字符串的字符个数,而不是字符串值。

- (NSComparisonResult)compare:(NSString *)string
     options:(NSStringCompareOptions) mask;

hasPrefix:是否以一个字符串开头

- (BOOL)hasPrefix:(NSString *)str;

hasSuffix:是否以一个字符串结尾

- (BOOL)hasSuffix:(NSString *)str;

rangeOfString:是否包含其他字符串

- (NSRange)rangeOfString:(NSString *)searchString;

componentsSeparatedByString:切分字符串

- (NSArray *)componentsSeparatedByString:(NSString *)separator;

stringByExpandingTildeInPath将路径展开为全路径

- (NSString *)stringByExpandingTildeInPath;

简单例子

int main(int argc, const char* argv[]) {
    NSString *string1 = @"Hello World";
    NSString *string2 = [NSString stringWithFormat:@"Hello World"];
    NSString *string3 = @"hello world";
    NSString *string4 = @"99";
    NSString *string5 = @"100";

    NSLog(@"%@ len is %lu", string1, [string1 length]);

    if ([string1 isEqualToString:string2]) {
        NSLog(@"equalToString");
    }

    if ([string1 compare:string2] == NSOrderedSame) {
        NSLog(@"same");
    }

    NSLog(@"compre result = %ld", [string1 compare:string3]);
    NSLog(@"CaseInsensitive compre result = %ld", 
        [string1 compare:string3 options:NSCaseInsensitiveSearch]);
    NSLog(@"compre result = %ld", [string4 compare:string5]);
    NSLog(@"Numeric compre result = %ld", 
        [string4 compare:string5 options:NSNumericSearch]);

    if ([string3 hasPrefix:@"hello"]) {
        NSLog(@"hasPrefix");
    }

    if ([string3 hasSuffix:@"world"]) {
        NSLog(@"hasSuffix");
    }

    return 0;
}

输出

Hello World len is 11
equalToString
same
compre result = -1
CaseInsensitive compre result = 0
compre result = 1
Numeric compre result = -1
hasPrefix
hasSuffix

1.2 NSMutableString类

stringWithCapicity:创建一个新NSMutableString

+ (NSMutableString *)stringWithCapacity:(NSUInteger)capacity;

appendString:添加新字符串
appendFormat:添加新格式化字符串

- (void)appendString:(NSString *)aString;
- (void)appendFormat:(NSString *)format, ...;

deleteCharactersInRange:删除字符串中的字符

- (void)deleteCharactersInRange:(NSRange)range

简单例子

int main(int argc, const char* argv[]) {
    NSMutableString *string = [NSMutableString stringWithCapacity:17];
    [string appendString:@"Hello World, "];
    [string appendFormat:@"%@", @"Welcome to Objective-C."];
    NSLog(@"%@", string);

    NSRange range = [string rangeOfString:@"World"];
    if (range.location != NSNotFound) {
        [string deleteCharactersInRange:range];
    }
    NSLog(@"%@", string);

    return 0;
}

输出

Hello World, Welcome to Objective-C.
Hello , Welcome to Objective-C.

2. 数组

NSArray是不可变数组,同样NSMutableArray是可变数组。两种关系如同NSStringNSMutableStringNSArray只能存储对象,不能存储基础数据(如int, float等),也不能存储nil(nil是结束标记)。

2.1 NSArray类

@符号直接创建一个数组。arrayWithObjects:方法创建数组。

+ (NSArray *)arrayWithObjects: ...;

count数组对象个数

- (NSUInteger)count;

objectAtIndex:获取特点索引处的对象,也可以通过中括号[]访问。

- (id)objectAtIndex:(NSUInteger)index;

componentsJoinedByString:合并NSArray中的元素,创建字符串。

- (NSString *)componentsJoinedByString:(NSString *)seperator;

简单例子

int main(int argc, const char* argv[]) {
    NSArray *array1 = @[@"one", @"two", @"three", @"four"];
    NSArray *array2 = [NSArray arrayWithObjects:@"one",
        @"two", @"three", @"four", nil];

    for (int index = 0; index < [array1 count]; index++) {
        NSLog(@"%@", [array1 objectAtIndex:index]);
    }

    for (int index = 0; index < [array2 count]; index++) {
        NSLog(@"%@", array2[index]);
    }

    NSLog(@"%@", [array1 componentsJoinedByString:@"--"]);

    return 0;
}

输出

one
two
three
four
one
two
three
four
one--two--three--four

2.2 可变数组NSMutableArray

arrayWithCapacity:创建可变数组

+ (id)arrayWithCapacity:(NSUInteger)numItems;

addObject:在数组末尾添加对象

- (void)addObject:(id)anObject;

removeObjectAtIndex:删除指定索引对象

- (void)removeObjectAtIndex:(NSUInteger)index;

简单例子

int main(int argc, const char* argv[]) {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:17];

    [array addObject:@"one"];
    [array addObject:@"two"];
    [array addObject:@"three"];

    for (int index = 0; index < [array count]; index++) {
        NSLog(@"%@", [array objectAtIndex:index]);
    }

    [array removeObjectAtIndex:1];
    for (int index = 0; index < [array count]; index++) {
        NSLog(@"%@", array[index]);
    }

    return 0;
}

输出

one
two
three
one
three

3. 枚举NSEnumerator类

NSArray对数组中每个元素执行相同操作,可以使用循环读取每个索引处的对象,也可以使用枚举NSEnumerator

- (NSEnumerator *)objectEnumerator;

nextObject读取下一个对象

- (id)nextObject;

in关键字可以快速遍历数组的每一个元素

for (id obj in array)

简单例子

int main(int argc, const char* argv[]) {
    NSArray *array = @[@"one", @"two", @"three", @"four"];
    NSEnumerator *enumerator = [array objectEnumerator];

    id string;
    while (string = [enumerator nextObject]) {
        NSLog(@"%@", string);
    }

    for (NSString *string in array) {
        NSLog(@"%@", string);
    }

    return 0;	
}

输出

one
two
three
four
one
two
three
four

4. 字典

NSDictionary类是不可变字典,同样NSMutableDictionary是可变字典。两种关系如同NSStringNSMutableString

4.1 NSDictionary类

@符号直接创建字典。key在前,value在后。

@{key:value, ...};

dictionaryWithObjectsAndKeys:创建字典。value在前,key在后。

+ (id)dictionaryWithObjectsAndKeys:(id)firstObject, ...;

objectForKey:读取指定关键字对象,也可以通过中括号[]访问。

- (id)objectForKey:(id)aKey;

简单例子

int main(int argc, const char* argv[]) {
    NSDictionary *dict1 = @{@"Mike":@"Mike Jordan", @"Tom":@"Tom Lee"};
    NSDictionary *dict2 = [NSDictionary dictionaryWithObjectsAndKeys:
            @"Mike Jordan", @"Mike", @"Tom Lee", @"Tom", nil];

    NSLog(@"%@", [dict1 objectForKey:@"Mike"]);
    NSLog(@"%@", dict2[@"Tom"]);

    for (id key in dict1) {
        NSLog(@"%@ : %@", key, dict1[key]);
    }

    return 0;
}

输出

Mike Jordan
Tom Lee
Tom : Tom Lee
Mike : Mike Jordan

4.2 NSMutableDictionary类

dictionaryWithCapacity:创建可变字典

+ (id)dictionaryWithCapacity:(NSUInteger)numItems;

setObject: forKey:为字典添加元素。

- (void)setObject:(id)anObject forKey:(id)aKey;

removeObjectForKey:删除关键字。

- (void)removeObjectForKey:(id)aKey;

简单例子

int main(int argc, const char* argv[]) {
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:17];
    [dict setObject:@"Mike Jordan" forKey:@"Mike"];
    [dict setObject:@"Tom Lee" forKey:@"Tom"];
    for (id key in dict) {
        NSLog(@"%@ : %@", key, dict[key]);
    }

    [dict removeObjectForKey:@"Tom"];
    for (id key in dict) {
        NSLog(@"%@ : %@", key, dict[key]);
    }
    return 0;
}

输出

Tom : Tom Lee
Mike : Mike Jordan
Mike : Mike Jordan

5. NSNumber类

NSNumber类用来封装基本类型。

+ (NSNumber *)numberWithChar:(char)value;
+ (NSNumber *)numberWithInt:(int)value;
+ (NSNumber *)numberWithFloat:(float)value;
+ (NSNumber *)numberWithBool:(BOOL)value;

也可以使用@符号创建

NSNumber *number;
number = @'x'; // 字符型
number = @1234; // 整型
number = @1.23; // 浮点型
number = @YES; // 布尔型

基本数据封装在NSNumber中后,可以使用方法重新获取。

- (char)charValue;
- (int)intValue;
- (float)floatValue;
- (BOOL)boolValue;

6. NSDate类

date返回当前时间

+ (id)date;

dateWithTimeIntervalSinceNow:返回距离当前时间一段时差的时间。

+ (id)dateWithTimeIntervalSinceNow:(int)sec;

initWithTimeInterval:sinceDate:返回距离指定时间一段时差的时间。

- (id)initWithTimeInterval:(int)sec sinceDate:(NSDate *)date;

laterDate:用于和另一时间相比,是否更晚。

- (BOOL)laterDate:(NSDate *)date;

earlierDate:用于和另一时间相比,是否更早。

- (BOOL)earlierDate:(NSDate *)date;

NSDateFormatter用来格式化NSDate

- (void)setDateFormat:(NSString *)format; // 指定格式
- (NSString *)stringFromDate:(NSDate *)date; // 格式化输出

简单例子

int main(int argc, const char* argv[]) {
    NSDate *currentDate = [NSDate date];
    NSDate *earlierDate = [NSDate dateWithTimeIntervalSinceNow:-60];
    NSDate *laterDate = [[NSDate alloc] initWithTimeInterval:60
                    sinceDate:currentDate];

    if ([currentDate laterDate:laterDate]) {
        NSLog(@"laterDate");
    }

    if ([currentDate earlierDate:earlierDate]) {
        NSLog(@"earlierDate");
    }

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSLog(@"%@", [df stringFromDate:currentDate]);
}

输出

laterDate
earlierDate
2019-07-16 11:05:08

7. NSNull类

NSArrayNSDictionary中不能存放nil值,使用NSNull表示没有值。
null方法创建NSNull

+ (NSNUll *)null;