黑马程序员——11、OC语言(Foundation框架的简单使用)

这篇博客介绍了Objective-C中Foundation框架的基础知识,包括CoreGraphics框架中的结构体如NSRange、NSPoint、NSSize、NSRect及其相关函数。同时讲解了Foundation框架中的集合类,如NSString、NSMutableString、NSArray、NSMutableArray、NSSet、NSMutableSet、NSDictionary、NSMutableDictionary的使用,并提到了NSNumber、NSValue和NSDate的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

---------------------- Java培训、Android培训、iOS培训、.Net培训期待与您交流! ---------------------


一、CoreGraphics框架中的结构体

先引入CoreGraphics框架(CG开头的框架,NS是NextStep的Foundation框架)

  1. NSRange

NSRange  ==》   (NSUInteger location, NSUInteger length)

初始化:NSRange r = NSMakeRange(2, 4);

    // NSString(NSRange):
    NSString *str = @"i love oc.";
    // 查找某个字符串在str中的范围
    // 如果找不到,length=0,location=NSNotFound=-1
    NSRange range = [str rangeOfString:@"java"];
    NSLog(@"loc=%ld, len=%ld", range.location, range.length);

  2. NSPoint/CGPoint

NSPoint/CGPoint  ==》 (CGFloat x, CGFloat y)

初始化: // 表示原点:CGPointZero == CGPointMake(0, 0)

        CGPoint p1 = NSMakePoint(5, 4); 

        CGPoint p2 = CGPointMake(10, 10); // 最常用

    // 以字符串形式快速打印CGPoint CGSize CGRect中的内容:
    NSString *str = NSStringFromPoint(p1);
    // NSString *str = NSStringFromSize(s1);
    // NSString *str = NSStringFromRect(r1);
    NSLog(@"%@", str);

  3. NSSize/CGSize

NSSize/CGSize ==》 (CGFloat width, CGFloat height)


初始化: // CGSizeZero == CGSizeMake(0,0)

           CGSize s1 = NSMakeSize(25, 26);

           CGSize s2 = CGSizeMake(10, 15); // 推荐

    // 以字符串形式快速打印CGPoint CGSize CGRect中的内容:
    // NSString *str = NSStringFromPoint(p1);
    NSString *str = NSStringFromSize(s1);
    // NSString *str = NSStringFromRect(r1);
    NSLog(@"%@", str);

  4. NSRect/CGRect

NSRect/CGRect ==》 (CGPoint, CGSize)  == ( (CGFloat x, CGFloat y), (CGFloat width, CGFloat height))


初始化:// CGRectZero == CGRectMake(0,0,0,0)                

        CGRect r1 = NSMakeRect(0, 0, 100, 50);

        CGRect r2 = CGRectMake(0, 0, 100, 50);   

        CGRect r3 = {{0, 0}, {100, 50}};

        CGRect r4 = {p2, s2};

    NSLog(@"x=%f, y=%f, width=%f, height=%f", r1.origin.x, r1.origin.y, r1.size.width, r1.size.height);
    
    // 以字符串形式快速打印CGPoint CGSize CGRect中的内容:
    // NSString *str = NSStringFromPoint(p1);
    // NSString *str = NSStringFromSize(s1);
    NSString *str = NSStringFromRect(r1);
    NSLog(@"%@", str);

  5. CGPoint、CGSize、CGRect结构体的其他函数

这些函数都是在CoreGraphics框架中的

    // 比较相不相同:
    BOOL b = CGPointEqualToPoint(CGPointMake(10, 10), CGPointMake(10, 10));
    NSLog(@"%d", b);
    
//    CGSizeEqualToSize(CGSize size1, CGSize size2)
//    CGRectEqualToRect(CGRect rect1, CGRect rect2)
    
    // 矩形是否包含某个点
    BOOL b2 = CGRectContainsPoint(CGRectMake(50, 40, 100, 50), CGPointMake(130, 70));
    NSLog(@"%d", b2);



二、Foundation框架中的集合类

集合:

OC                           JAVA

NSArray                    ArrayList

NSSet                      HashSet

NSDictionary               HashMap

  1. NSString \ NSMutableString

NSString:不可变字符串(内容不可改变)

NSMutableString:可变字符串(可以改变字符串的内容)

(1)NSString

字符串的创建:

    NSString *str = @"Jack";
    // NSString *str1 = [[NSString alloc] initWithString:@"range"];
    NSString *str2 = [[NSString alloc] initWithFormat:@"age is %d", 3];
    
    // C字符串 --》 OC字符串
    NSString *str3 = [[NSString alloc] initWithUTF8String:"ewrty"];
    // OC字符串  --> C字符串
    const char *s = [str3 UTF8String];
    
    // NSUTF8StringEncoding 转码格式:文件中有中文就可以用这个
    NSString *str4 = [[NSString alloc] initWithContentsOfFile:@"/Users/qitan/Desktop/learning/1.txt" encoding:NSUTF8StringEncoding error:nil];
    NSURL *url = [NSURL URLWithString:@"file:///Users/qitan/Desktop/learning/1.txt" ];
    NSString *str5 = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
    
    NSLog(@"\n%@", str5);

系统自带的对象方法一般都有一个类方法与之对应,不需要alloc和init

直接调用NSString的类方法进行字符串的创建:

[NSString stringWithFormat:(NSString *), ...]

[NSString stringWithContentsOfFile:(NSString *) encoding:(NSStringEncoding) error:(NSError *__autoreleasing *)]

[NSString stringWithContentsOfURL:(NSURL *) encoding:(NSStringEncoding) error:(NSError *__autoreleasing *)]

字符串的导出:

[@"im tried~~\nwow!" writeToFile:@"/Users/qitan/Desktop/learning/2.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];

NSString *str = @"werty";
NSURL *url = [NSURL fileURLWithPath:@"/Users/qitan/Desktop/learning/2.txt"];
[str writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:nil];

字符串中的length方法:计算字数,不是字符数。

    NSString *name2 = @"哈哈Jack"; //6
    //length方法算的是字数,不是字符数
    NSLog(@"%ld", [name2 length]); //%ld

(2)NSMutableString

NSString的很多方法在NSMutableString里都有,而且还有自己的一些方法:

NSMutableString *s1 = [NSMutableString stringWithFormat:@"age is %d", 10];

// 拼接内容到s1的后面 (这个函数返回值为void)
[s1 appendString:@" 11 12"];

// 删除某写range的字符[s1 deleteCharactersInRange:[s1 rangeOfString:@"is"]]; // 推荐
[s1 deleteCharactersInRange:NSMakeRange(4, 2)];

NSLog(@"%@", s1);

NSString *s2 = [NSString stringWithFormat:@"age is %d", 10];
// 通过s2和@" 11 12 13" --》 s3
NSString *s3 = [s2 stringByAppendingString:@" 11 12 13"];

  2. NSArray \ NSMutableArray

NSArray:不可变数组

NSMutableArray:可变数组

(1)NSArray

* 有序

* 快速创建(不可变的):@[]

* 快速访问元素:数组名[i]

基本使用:

/*1.创建对象数组*****************************/
// OC数组不能存放nil值(结束标志不能过多)
// OC数组只能存放OC对象,不能存放非OC对象类型,比如int、struct、enum等

// 这个数组永远都是空数组
NSArray *array = [NSArray array];

NSArray *array2 = [NSArray arrayWithObject:@"jack"];

// nil是数组元素结束的标志
NSArray *array3 = [NSArray arrayWithObjects:@"jouse", @"rose", nil];

// @[] 代表创建数组对象
// 快速创建数组,编译器特性
NSArray *array4 = @[@"rose", @"jack", @"jose"];

/*2.对象数组元素计数*****************************/
// [array3 count];
long c = array3.count;
NSLog(@"%ld", c);

/*3.对象数组元素访问*****************************/
// NSLog(@"%@", [array3 objectAtIndex:1]);
NSLog(@"%@", array3[0]); // 也可以跟C一样访问数组元素(编译器特性)

遍历数组元素:

Person *p = [[Person alloc] init];
NSArray *arr = @[p, @"jack", @"rose"];
// 不推荐使用
for (int i=0; i<arr.count; i++) {
    NSLog(@"%@", arr[i]);
}

// 快速遍历
// id obj:数组中的每一个元素
// 缺点:不知道循环的第几次
//int i = 0;
//    for(id obj in arr)
//    {
//        // 找出obj元素在数组中的位置
//        long i = [arr indexOfObject:obj];
//
//        NSLog(@"arr[%ld]=%@", i, obj);
//        //i++;
//
//        if (i == 1) {
//            break;
//        }
//    }

// 【推荐】既然是对象就用对象方法。。
[arr enumerateObjectsUsingBlock:
 // 每遍历到一个元素,就会调用一次block
 // 并且当前元素和索引位置当做参数传递给block
 ^(id obj, NSUInteger idx, BOOL *stop) {
     
     NSLog(@"%ld--%@", idx, obj);
     
     if (idx == 1) {
         // 停止遍历
         *stop = YES;
     }
 }];

(2)NSMutableArray

NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"rose", @"write", nil];

// 添加元素
[arr addObject:[[Person alloc] init]];
[arr addObject:@"jack"];

// 错误写法!
// [arr addObject:nil];

// 删除所有元素
// [arr removeAllObjects];
// 删除指定元素
// [arr removeObject:@"jack"];
// 删除指定下标的元素
// [arr removeObjectAtIndex:2];


NSLog(@"%@", arr);
NSLog(@"%ld", arr.count);


// @[] 只创建不可变数组NSArray
/* 错误写法:unrecognized selector sent to instance 0x100109960
NSMutableArray *arr = @[@"jack", @"rose"];
[arr addObject:@"jim"];
*/

  3. NSSet \ NSMutableSet

NSSet:不可变集合

NSMutableSet:可变集合

NSSet和NSArray的对比:

1》共同的

* 都是集合,都能存放多个OC对象

* 只能存放OC对象,不能存放非OC对象类型(基本数据类型:int、char、结构体、枚举)

* 本身 不可变,都有一个可变的子类

2》不同点

* NSArray有顺序,NSSet无序

(1)NSSet

* 无序

NSSet *s1 = [NSSet set];
NSSet *s2 = [NSSet setWithObjects:@"rose", @"jack4",@"rose2", @"jack", nil];

// 随机取出某个元素(随机的)
NSString *str = [s2 anyObject];

NSLog(@"%@", str);
NSLog(@"%ld", s2.count);

(2)NSMutableSet

NSMutableSet *s1 = [NSMutableSet set];

[s1 addObject:@"hack"];
[s1 addObject:@"rose"];

[s1 removeObject:@"hack"];


  4. NSDictionary \ NSMutableDictionary

字典:

索引 --> 文字内容

key  -->   value

* 快速创建(不可变的):@{key1: value1, key2: value2}

* 快速访问元素:字典名[key]

字典是无序的,里面存储的都是键值对。

NSDictionary:不可变的字典

NSMutableDictionary:可变的字典

(1)NSDictionary

* 无序

/*
 NSDictionary *dict1 = [NSDictionary dictionary];
 NSDictionary *dict2 = [NSDictionary dictionaryWithObject:@"jacken" forKey:@"name"];
 
 NSArray *keys = @[@"name", @"address"];
 NSArray *values = @[@"jack", @"北京"];
 NSDictionary *dict3 = [NSDictionary dictionaryWithObjects:values forKeys:keys];
 
 NSDictionary *dict4 = [NSDictionary dictionaryWithObjectsAndKeys:@"rose",@"name", @"beijing",@"address", @"46454542",@"qq", nil];
 
 id obj = [dict2 objectForKey:@"name"];
 id obj2 = [dict3 objectForKey:@"name"];
 id obj3 = [dict4 objectForKey:@"qq"];
 
 NSLog(@"%@", obj3);
 */

// Xxode特性
NSDictionary *dict = @{@"name": @"jim", @"address": @"beijing", @"qq": @"64565844"};

// 取出某个key对象对应的value对象
id obj = [dict objectForKey:@"address"];

id obj1 = dict[@"qq"];

NSLog(@"%@", obj1);

// 返回键值对的个数
NSLog(@"%ld", dict.count);
</pre><pre name="code" class="objc">    // 字典的遍历
    // 字典不允许有相同的key,但允许有相同的value
    // 无序的
    NSDictionary *dict = @{@"name": @"jim", @"address": @"beijing", @"qq": @"64565844"};
    
//    NSArray *keys = [dict allKeys];
//    for (int i=0; i<dict.count; i++) {
//        NSString *key = keys[i];
//        NSString *object = dict[key];
//        
//        NSLog(@"%@ - %@", key, object);
//    }
    
    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSLog(@"%@ - %@", key, obj);
    }];

    NSArray *persons =@[
  @{@"name": @"jack", @"no": @"001"},
  @{@"name": @"rose", @"no": @"002"},
  @{@"name": @"aaa", @"no": @"003"},
  @{@"name": @"bbb", @"no": @"004"}
  ];

NSDictionary *rose = persons[1];
NSLog(@"%@", rose);

// 先取出2对应位置的字典,再取出字典中name这个key对应的数据
NSLog(@"%@", persons[2][@"name"]);


(2)NSMutableDictionary

NSMutableDictionary *dict = [NSMutableDictionary dictionary];

// 添加键值对
[dict setObject:@"jim" forKey:@"name"];
[dict setObject:@"beijing" forKey:@"address"];
// 覆盖以前的值,一个字典只有一个key
[dict setObject:@"jack" forKey:@"name"];

// 删除键值对
//    [dict removeObjectForKey:@"address"];

NSLog(@"%@", dict);
/* 错误写法 找不到setObject方法
    NSMutableDictionary *dict = @{@"name": @"jim", @"address": @"beijing", @"qq": @"64565844"};
    
    [dict setObject:@"rose" forKey:@"name"];
     */


NSMutableDictionary不能使用不可变字典的创建方式:@{key : value, ...};


  5. NSNumber

把基本数据类型(int、double、char、BOOL等数字)包装成NSNumber对象

// 基本数据类型 ---》 对象
NSNumber *n = [NSNumber numberWithDouble:10.5];

// 对象 ---》 基本数据类型
double d = [n doubleValue];

int a = 20;
NSString *str = [NSString stringWithFormat:@"%d", a];
int b = [str intValue];

// @20 将20包装成一个NSNumber对象
// @10.5    @YES    @'A'
NSDictionary *dict =
@{
  @"name": @"jack",
  @"age": @20
  };

@"A"; // NSString
@'A'; // NSNumber

// 将age变量包装成NSNumber对象
int age = 100;
@(age);

  6. NSValue

NSNumber 之所以能包装基本数据类型为对象,是因为继承了NSValue。

NSValue功能更加强大,对CG框架的结构体也可以包装。

// 将结构体包装成OC对象
CGPoint p = CGPointMake(10, 10);
// 结构体 --》 NSValue对象
NSValue *val = [NSValue valueWithPoint:p];

NSArray *arr = @[val, val];

// NSValue对象 --> 结构体
CGPoint p2 = [val pointValue];

  7. NSDate

日期、时间类型

NSDate的基本使用:

// 创建一个时间对象
NSDate *date = [NSDate date];

// 打印的时间是0时区的时间(北京-东8区)
NSLog(@"%@", date);

// 5 秒
NSDate *date2 = [NSDate dateWithTimeInterval:5 sinceDate:date];
NSLog(@"%@", date2);

// NSTimeInterval == double
//    NSTimeInterval seconds = [date2 timeIntervalSince1970];
NSTimeInterval seconds = [date2 timeIntervalSinceNow]; // 调用程序的时间
NSLog(@"%f", seconds);

NSDate和NSString之间的相互转换

/*Date转换为NSString*********************/
NSDate *date = [NSDate date];

// 日期格式化类
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

// y-年 M-月 d-日
// HH-24时(hh-12时) mm-分 ss-秒
formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";

NSString *str = [formatter stringFromDate:date];

NSLog(@"%@", str);

/*NSString转换为Date*********************/
NSString *time = @"2012/05/12 16:45";
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
formatter2.dateFormat = @"yyyy/MM/dd HH:mm";

NSDate *date2 = [formatter2 dateFromString:time];
NSLog(@"%@", date2); // 自动输出为0时区的时间




                 CGPoint p2 = CGPointMake(10, 10); // 最常用
初始化: // CGSizeZero == CGSizeMake(0,0)
初始化:// CGRectZero == CGRectMake(0,0,0,0)
        CGRect r3 = {{0, 0}, {100, 50}};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值