Foundation框架的小总结

一、Foundation框架—结构体

一、基本知识

Foundation框架中包含了很多开发中常用的数据类型,如结构体,枚举,类等,是其他ios框架的基础。

如果要想使用foundation框架中的数据类型,那么包含它的主头文件就可以了。即#import<foundation/foundation.h>

补充:core foundation框架相对底层,里面的代码几乎都是c语言的,而foundation中是OC的。

 

二、常用的结构体介绍及简单使用

常用的结构体:

 

(一)NSRang的基本使用

     NSRange(location length)          表示范围

     NSPoint\CGPoint                   表示坐标

     NSSize\CGSize                      表示UI元素的尺寸

     NSRect\CGRect (CGPint CGSize)    表示一个UI元素的位置和尺寸

创建变量

 1 //
 2 //  main.m
 3 //  Foundation1-结构体
 4 //
 5 //  Created by mj on 13-4-5.
 6 //  Copyright (c) 2013年 itcast. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 
11 void test() {
12     // 定义了Date这种结构体类型
13     struct Date {
14         int year;
15         int month;
16         int day;
17     };
18     
19     // 定义结构体变量
20     struct Date d = {2013, 4, 5};
21     d.day = 6;
22 }
23 
24 void test1() {
25     typedef struct Date {
26         int year;
27         int month;
28         int day;
29     } MyDate;
30     
31     MyDate d = {2013, 4, 5};
32 }
33 
34 void range() {
35     NSRange range = NSMakeRange(8, 10);
36     
37     NSLog(@"location:%zi", range.location);
38     NSLog(@"length:%zi", range.length);
39     
40     NSString *str =  NSStringFromRange(range);
41     NSLog(@"%@", str);
42     // NSLog(@"%@", range); 错误的做法,%@代表着OC对象
43 }
44 
45 void point() {    
46     // NSPoint p;
47     CGPoint p;
48     p.x = 1;
49     p.y = 10;
50     
51     p = NSMakePoint(10, 9);
52     
53     // 常见的方式
54     p = CGPointMake(8, 9);
55     
56     NSString *str = NSStringFromPoint(p);
57     NSLog(@"%@", str);
58 }
59 
60 void size() {
61     CGSize size; // NSSize size;
62     size.width = 100;
63     size.height = 90;
64     
65     size = NSMakeSize(90, 80);
66     
67     size = CGSizeMake(10, 8);
68     
69     NSString *str = NSStringFromSize(size);
70     NSLog(@"%@", str);
71 }
72 
73 void rect() {
74     NSRect rect; // CGRect rect;
75     rect.origin.x = 10;
76     rect.origin.y = 11;
77     
78     rect.size.width = 100;
79     rect.size.height = 90;
80     
81     rect = NSMakeRect(10, 10, 80, 80);
82     
83     rect = CGRectMake(8, 9, 10, 90);
84     
85     NSString *str = NSStringFromRect(rect);
86     NSLog(@"%@", str);
87 }
88 
89 int main(int argc, const char * argv[])
90 {
91     @autoreleasepool {
92         rect();
93     }
94     return 0;
95 }

 

 

二、Foundation框架—字符串

 

一、Foundation框架中一些常用的类

字符串型:

NSString:不可变字符串

NSMutableString:可变字符串

集合型:

1)

NSArray:OC不可变数组

NSMutableArray:可变数组

2)

NSSet:

NSMutableSet:

3)

NSDictiorary

NSMutableDictiorary

其它:

NSDate

NSObject

 

二、NSString和NSMutableString

种创建字符串的形式

 

  1 #import <Foundation/Foundation.h>
  2 
  3 #pragma mark NSString的创建
  4 void stringCreate() {
  5     // char *s = "A String!"; // C语言中的字符串
  6     
  7     // 这种方式创建出来的字符串是不需要释放的
  8     NSString *str1 = @"A String!";
  9     
 10     NSString *str2 = [[NSString alloc] init];
 11     str2 = @"A String!";
 12     [str2 release];
 13     
 14     NSString *str3 = [[NSString alloc] initWithString:@"A String!"];
 15     [str3 release];
 16     // 不需要管理内存
 17     str3 = [NSString stringWithString:@"A String!"];
 18     
 19     
 20     NSString *str4 = [[NSString alloc] initWithUTF8String:"A String!"];
 21     [str4 release];
 22     str4 = [NSString stringWithUTF8String:"A String!"];
 23     
 24     NSString *str5 = [[NSString alloc] initWithFormat:@"My age is %i and height is %.2f", 19, 1.55f];
 25     
 26     // 这句代码放在中间会造成2个错误:
 27     // 1.前面创建的字符串没有被释放
 28     // 2.后面创建的字符串会释放过度,造成野指针错误
 29     // str5 = [NSString stringWithFormat:@"My age is %i and height is %.2f", 19, 1.55f];
 30     
 31     NSLog(@"str5:%@", str5);
 32     [str5 release];
 33     
 34     str5 = [NSString stringWithFormat:@"My age is %i and height is %.2f", 19, 1.55f];
 35 }
 36 
 37 void test(NSString **str) {
 38     *str = @"123";
 39     // s = @"123";
 40 }
 41 
 42 void stringCreate2() {
 43     // 从文件中读取文本
 44     NSString *path = @"/Users/apple/Desktop/test.txt";
 45     // 这个方法已经过期,不能解析中文
 46     // NSString *str1 = [NSString stringWithContentsOfFile:path];
 47     
 48     // 定义一个NSError变量
 49     NSError *error;
 50     // 指定字符串编码为UTF-8: NSUTF8StringEncoding
 51     NSString *str1 = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
 52     if (error == nil) { // 没有错误信息
 53         NSLog(@"读取文件成功:%@", str1);
 54     } else {
 55         NSLog(@"读取文件失败:%@", error);
 56     }
 57     
 58     NSURL *url = [NSURL URLWithString:@"file:///Users/apple/Desktop/test.txt"];
 59     NSString *str2 = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
 60     NSLog(@"%@", str2);
 61     
 62     NSURL *url2 = [NSURL URLWithString:@"http://www.baidu.com"];
 63     NSString *str3 = [NSString stringWithContentsOfURL:url2 encoding:NSUTF8StringEncoding error:nil];
 64     NSLog(@"%@", str3);
 65 }
 66 
 67 #pragma mark 字符串的导出
 68 void stringExport() {
 69     NSString *str = @"123456我是字符串!!!!";
 70     // 如果文件不存在,会自动创建文件
 71     // 如果文件夹不存在,会直接报错
 72     NSString *path = @"/Users/apple/Desktop/abc.txt";
 73     
 74     NSError *error;
 75     // 编码指定错误也会报错
 76     // YES代表要进行原子性操作,也就是会创建一个中间的临时文件
 77     [str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
 78     if (error) {
 79         // [error localizedDescription]会返回主要的错误信息
 80         NSLog(@"写入失败:%@", [error localizedDescription]);
 81     } else {
 82         NSLog(@"写入成功");
 83     }
 84 }
 85 
 86 //void test2(int *p) {
 87 //    *p = 9;// a = 9;
 88 //}
 89 
 90 int main(int argc, const char * argv[])
 91 {
 92 
 93     @autoreleasepool {
 94 //        int a = 10;
 95 //        test2(&a);
 96 //        NSLog(@"%i", a);
 97         
 98         stringExport();
 99         
100 //        NSString *s = @"456";
101 //        
102 //        test(&s);
103 //        
104 //        NSLog(@"%@", s);
105     }
106     return 0;
107 }

 

  1 //
  2 //  main.m
  3 //  NSString
  4 //
  5 //  Created by mj on 13-4-5.
  6 //  Copyright (c) 2013年 itcast. All rights reserved.
  7 //
  8 
  9 #import <Foundation/Foundation.h>
 10 
 11 #pragma mark NSString的创建
 12 void stringCreate() {
 13     // char *s = "A String!"; // C语言中的字符串
 14     
 15     // 这种方式创建出来的字符串是不需要释放的
 16     NSString *str1 = @"A String!";
 17     
 18     NSString *str2 = [[NSString alloc] init];
 19     str2 = @"A String!";
 20     [str2 release];
 21     
 22     NSString *str3 = [[NSString alloc] initWithString:@"A String!"];
 23     [str3 release];
 24     // 不需要管理内存
 25     str3 = [NSString stringWithString:@"A String!"];
 26     
 27     
 28     NSString *str4 = [[NSString alloc] initWithUTF8String:"A String!"];
 29     [str4 release];
 30     str4 = [NSString stringWithUTF8String:"A String!"];
 31     
 32     NSString *str5 = [[NSString alloc] initWithFormat:@"My age is %i and height is %.2f", 19, 1.55f];
 33     
 34     // 这句代码放在中间会造成2个错误:
 35     // 1.前面创建的字符串没有被释放
 36     // 2.后面创建的字符串会释放过度,造成野指针错误
 37     // str5 = [NSString stringWithFormat:@"My age is %i and height is %.2f", 19, 1.55f];
 38     
 39     NSLog(@"str5:%@", str5);
 40     [str5 release];
 41     
 42     str5 = [NSString stringWithFormat:@"My age is %i and height is %.2f", 19, 1.55f];
 43 }
 44 
 45 void test(NSString **str) {
 46     *str = @"123";
 47     // s = @"123";
 48 }
 49 
 50 void stringCreate2() {
 51     // 从文件中读取文本
 52     NSString *path = @"/Users/apple/Desktop/test.txt";
 53     // 这个方法已经过期,不能解析中文
 54     // NSString *str1 = [NSString stringWithContentsOfFile:path];
 55     
 56     // 定义一个NSError变量
 57     NSError *error;
 58     // 指定字符串编码为UTF-8: NSUTF8StringEncoding
 59     NSString *str1 = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
 60     if (error == nil) { // 没有错误信息
 61         NSLog(@"读取文件成功:%@", str1);
 62     } else {
 63         NSLog(@"读取文件失败:%@", error);
 64     }
 65     
 66     NSURL *url = [NSURL URLWithString:@"file:///Users/apple/Desktop/test.txt"];
 67     NSString *str2 = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
 68     NSLog(@"%@", str2);
 69     
 70     NSURL *url2 = [NSURL URLWithString:@"http://www.baidu.com"];
 71     NSString *str3 = [NSString stringWithContentsOfURL:url2 encoding:NSUTF8StringEncoding error:nil];
 72     NSLog(@"%@", str3);
 73 }
 74 
 75 #pragma mark 字符串的导出
 76 void stringExport() {
 77     NSString *str = @"123456我是字符串!!!!";
 78     // 如果文件不存在,会自动创建文件
 79     // 如果文件夹不存在,会直接报错
 80     NSString *path = @"/Users/apple/Desktop/abc.txt";
 81     
 82     NSError *error;
 83     // 编码指定错误也会报错
 84     // YES代表要进行原子性操作,也就是会创建一个中间的临时文件
 85     [str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
 86     if (error) {
 87         // [error localizedDescription]会返回主要的错误信息
 88         NSLog(@"写入失败:%@", [error localizedDescription]);
 89     } else {
 90         NSLog(@"写入成功");
 91     }
 92 }
 93 
 94 //void test2(int *p) {
 95 //    *p = 9;// a = 9;
 96 //}
 97 
 98 int main(int argc, const char * argv[])
 99 {
100 
101     @autoreleasepool {
102 //        int a = 10;
103 //        test2(&a);
104 //        NSLog(@"%i", a);
105         
106         stringExport();
107         
108 //        NSString *s = @"456";
109 //        
110 //        test(&s);
111 //        
112 //        NSLog(@"%@", s);
113     }
114     return 0;
115 }

 

(四)URL补充内容

Url:资源路径

格式:协议头:/路径

网络路径协议头:http

本地文件以file为协议头

ftp为协议头,说明资源是ftp服务器上的。

 

 

 

三、Foundation框架—集合

 

1、NSArray和NSMutableArray

(一)NSArray不可变数组

(1)NSArray的基本介绍

NSArray是OC中使用的数组,是面向对象的,以面向对象的形式操纵对象,是不可变数组。

C语言数组有一个缺点即数组中只能存放同种数据类型的元素。

OC数组只能存放OC对象,不能存放非OC对象,如int,结构体和枚举等。

 (二)NSMutableArray可变数组

(1)NSMutableArray的基本使用

注意:NSMutableArray继承自NSArray,几乎拥有NSArray的一切方法。

 

  1 #import <Foundation/Foundation.h>
  2 #import "Person.h"
  3 
  4 
  5 /*
  6  
  7 NSArray :不可变数组
  8  
  9  
 10 NSMutableArray : 可变数组
 11  */
 12 
 13 int main()
 14 {
 15     // @[] 只创建不可变数组NSArray
 16     /* 错误写法
 17     NSMutableArray *array = @[@"jack", @"rose"];
 18     
 19     [array addObject:@"jim"];
 20     */
 21     
 22     
 23     //NSArray *array = @[@"jack", @"rose"];
 24     
 25     return 0;
 26 }
 27 
 28 // 可变数组的基本使用
 29 void use3()
 30 {
 31     NSMutableArray *array = [NSMutableArray arrayWithObjects:@"rose", @"jim", nil];
 32     
 33     // 添加元素
 34     [array addObject:[[Person alloc] init]];
 35     
 36     [array addObject:@"jack"];
 37     
 38     // 删除元素
 39     //[array removeAllObjects];
 40     // 删除指定的对象
 41     // [array removeObject:@"jack"];
 42     [array removeObjectAtIndex:0];
 43     
 44     // 错误写法
 45     // [array addObject:nil];
 46     
 47     
 48     NSLog(@"%@", array);
 49     
 50     NSLog(@"%ld", array.count);
 51 }
 52 
 53 // 遍历数组
 54 void use2()
 55 {
 56     Person *p = [[Person alloc] init];
 57     
 58     NSArray *array = @[p, @"rose", @"jack"];
 59     
 60     //    for (int i = 0; i<array.count; i++)
 61     //    {
 62     //        NSLog(@"%@", array[i]);
 63     //    }
 64     
 65     // id obj代表着数组中的每一个元素
 66     //int i = 0;
 67     //    for (id obj in array)
 68     //    {
 69     //        // 找出obj元素在数组中的位置
 70     //        NSUInteger i = [array indexOfObject:obj];
 71     //
 72     //        NSLog(@"%ld - %@", i, obj);
 73     //        //i++;
 74     //
 75     //        if (i==1)
 76     //        {
 77     //            break;
 78     //        }
 79     //    }
 80     
 81     [array enumerateObjectsUsingBlock:
 82      
 83      // 每遍历到一个元素,就会调用一次block
 84      // 并且当前元素和索引位置当做参数传给block
 85      ^(id obj, NSUInteger idx, BOOL *stop)
 86      {
 87          NSLog(@"%ld - %@", idx, obj);
 88          
 89          
 90          if (idx == 0)
 91          {
 92              // 停止遍历
 93              *stop = YES;
 94          }
 95          
 96      }];
 97     
 98     
 99     //    void ^(myblock)(id, NSUInteger, BOOL *) = ^(id obj, NSUInteger idx, BOOL *stop)
100     //    {
101     //        NSLog(@"%ld - %@", idx, obj);
102     //
103     //
104     //        if (idx == 0)
105     //        {
106     //            // 停止遍历
107     //            *stop = YES;
108     //        }
109     //    };
110     //
111     //    for (int i = 0; i<array.count; i++)
112     //    {
113     //        // 用来标记是否需要停止遍历
114     //        BOOL isStop = NO;
115     //
116     //        // 取出元素
117     //        id obj = array[i];
118     //        
119     //        myblock(obj, i, &isStop);
120     //        
121     //        
122     //        if (isStop)
123     //        {
124     //            break;
125     //        }
126     //    }
127 
128 }
129 
130 void use()
131 {
132     /*
133      int a = 5;
134      
135      int ages[10] = {1, 90, 89, 17};
136      
137      Person *p = [[Person alloc] init];
138      Person *persons[5] = {p,  [[Person alloc] init]};
139      */
140     
141     // OC数组不能存放nil值
142     // OC数组只能存放OC对象、不能存放非OC对象类型,比如int、struct、enum等
143     
144     // 这个array永远是空数组
145     // NSArray *array = [NSArray array];
146     
147     
148     /*
149      1.NSArray的创建
150      */
151     NSArray *array2 = [NSArray arrayWithObject:@"jack"];
152     
153     // nil是数组元素结束的标记
154     NSArray *array3 = [NSArray arrayWithObjects:@"jack", @"rose", nil];
155     // [array2 count];
156     
157     //NSArray *array4 = [NSArray arrayWithObjects:@"jack", @"rose", @"4324324", nil];
158     
159     // 快速创建一个NSArray对象
160     NSArray *array4 = @[@"jack", @"rose", @"4324324"];
161     
162     
163     /*
164      2.NSArray的元素个数
165      */
166     NSLog(@"%ld", array3.count);
167     
168     
169     /*
170      3.NSArray中元素的访问
171      */
172     NSLog(@"%@", [array3 objectAtIndex:1]);
173     
174     //array3[1];
175     NSLog(@"%@", array3[0]);
176 }

 

2、NSSet和NSMutableSet

 

  1.NSSet不可变集合

  2.NSMutableSet可变集合

 

 1 //
 2 //  main.m
 3 //  05-NSSet
 4 //
 5 //  Created by apple on 13-8-12.
 6 //  Copyright (c) 2013年 itcast. All rights reserved.
 7 //
 8 
 9 /*
10  NSSet和NSArray的对比
11  1> 共同点
12  * 都是集合,都能存放多个OC对象
13  * 只能存放OC对象,不能存放非OC对象类型(基本数据类型:int、char、float等,结构体,枚举)
14  * 本身都不可变,都有一个可变的子类
15  
16  2> 不同点
17  * NSArray有顺序,NSSet没有顺序
18  */
19 
20 #import <Foundation/Foundation.h>
21 
22 int main()
23 {
24     NSMutableSet *s = [NSMutableSet set];
25     
26     // 添加元素
27     [s addObject:@"hack"];
28     
29     // 删除元素
30     // [s removeObject:<#(id)#>];
31     return 0;
32 }
33 
34 // set的基本使用
35 void test()
36 {
37     NSSet *s = [NSSet set];
38     
39     NSSet *s2 = [NSSet setWithObjects:@"jack",@"rose", @"jack2",@"jack3",nil];
40     
41     // 随机拿出一个元素
42     NSString *str =  [s2 anyObject];
43     
44     NSLog(@"%@", str);
45     
46     //NSLog(@"%ld", s2.count);
47 }

 

练习

//
//  main.m
//  04-计算代码行数
//
//  Created by apple on 13-8-12.
//  Copyright (c) 2013年 itcast. All rights reserved.
//

/*
 * 考察NSString、NSArray的使用
 * NSFileManager
 */

#import <Foundation/Foundation.h>


// 计算文件的代码行数
/*
 path : 文件的全路径(可能是文件夹、也可能是文件)
 返回值 int :代码行数
 */
NSUInteger codeLineCount(NSString *path)
{
    // 1.获得文件管理者
    NSFileManager *mgr = [NSFileManager defaultManager];
    
    // 2.标记是否为文件夹
    BOOL dir = NO; // 标记是否为文件夹
    // 标记这个路径是否存在
    BOOL exist = [mgr fileExistsAtPath:path isDirectory:&dir];
    
    // 3.如果不存在,直接返回0
    if(!exist)
    {
        NSLog(@"文件路径不存在!!!!!!");
        return 0;
    }
    
    // 代码能来到着,说明路径存在
    
    
    if (dir)
    { // 文件夹
        // 获得当前文件夹path下面的所有内容(文件夹、文件)
        NSArray *array = [mgr contentsOfDirectoryAtPath:path error:nil];
        
        // 定义一个变量保存path中所有文件的总行数
        int count = 0;
        
        // 遍历数组中的所有子文件(夹)名
        for (NSString *filename in array)
        {
            // 获得子文件(夹)的全路径
            NSString *fullPath = [NSString stringWithFormat:@"%@/%@", path, filename];
            
            // 累加每个子路径的总行数
            count += codeLineCount(fullPath);
        }
        
        return count;
    }
    else
    { // 文件
        // 判断文件的拓展名(忽略大小写)
        NSString *extension = [[path pathExtension] lowercaseString];
        if (![extension isEqualToString:@"h"]
            && ![extension isEqualToString:@"m"]
            && ![extension isEqualToString:@"c"])
        {
            // 文件拓展名不是h,而且也不是m,而且也不是c
            return 0;
        }
        
        // 加载文件内容
        NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
        
        // 将文件内容切割为每一行
        NSArray *array = [content componentsSeparatedByString:@"\n"];
        
        // 删掉文件路径前面的/Users/apple/Desktop/iOS课堂共享/0722课堂共享/
        NSRange range = [path rangeOfString:@"/Users/apple/Desktop/iOS课堂共享/0722课堂共享/"];
        NSString *str = [path stringByReplacingCharactersInRange:range withString:@""];
        
        // 打印文件路径和行数
        NSLog(@"%@ - %ld", str, array.count);
        
        return array.count;
    }
}

int main()
{
    
    NSUInteger count = codeLineCount(@"/Users/apple/Desktop/iOS课堂共享/0722课堂共享");
    
    NSLog(@"%ld", count);
    return 0;
}

void test()
{
    NSString *str = @"jack\nrose\njim\njake";
    
    [str writeToFile:@"/Users/apple/Desktop/abc.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    
    NSArray *array = [str componentsSeparatedByString:@"\n"];
    
    for (NSString *line in array)
    {
        NSLog(@"%@", line);
    }
    
    
    //int count = codeLineCount(@"/Users/apple/Desktop/iOS课堂共享/0722课堂共享/0811/代码/04-block/04-block/main.m");
    
    //NSLog(@"count=%d", count);
}

 

3、NSDictionary和NSMutableDictionary

 

(一)NSDictionary不可变字典

(1)介绍

现实中的字典:根据索引找到具体的内容

OC中的NSDictionary:根据key找到value。里面存储的东西都是键值对。 

注意:快速创建字典是编译器特性。

(二)NSMutableDictionary可变字典

  1 //
  2 //  main.m
  3 //  06-NSDictionary
  4 //
  5 //  Created by apple on 13-8-12.
  6 //  Copyright (c) 2013年 itcast. All rights reserved.
  7 //
  8 
  9 
 10 /*
 11  集合
 12  1.NSArray\NSMutableArray
 13  * 有序
 14  * 快速创建(不可变):@[obj1, obj2, obj3]
 15  * 快速访问元素:数组名[i]
 16  
 17  2.NSSet\NSMutableSet
 18  * 无序
 19  
 20  3.NSDictionary\NSMutableDictionary
 21  * 无序
 22  * 快速创建(不可变):@{key1 : value1,  key2 : value2}
 23  * 快速访问元素:字典名[key]
 24  */
 25 
 26 #import <Foundation/Foundation.h>
 27 
 28 int main()
 29 {
 30     NSArray *persons = @[
 31     @{@"name" : @"jack", @"qq" : @"432423423", @"books": @[@"5分钟突破iOS编程", @"5分钟突破android编程"]},
 32     @{@"name" : @"rose", @"qq" : @"767567"},
 33     @{@"name" : @"jim", @"qq" : @"423423"},
 34     @{@"name" : @"jake", @"qq" : @"123123213"}
 35     ];
 36     
 37     // 
 38     // NSDictionary *jim = persons[2];
 39     
 40     
 41     // 
 42     NSString *bookName = persons[0][@"books"][1];
 43     NSLog(@"%@", bookName);
 44     //NSArray *array = persons[0][@"books"];
 45     
 46     //NSLog(@"%@", array);
 47     
 48     // 先取出1位置对应的字典
 49     // 再取出字典中qq这个key对应的数据
 50     //NSLog(@"%@", persons[1][@"qq"]);
 51     
 52     // NSLog(@"%@", jim);
 53     return 0;
 54 }
 55 
 56 void use4()
 57 {
 58     // 字典不允许有相同的key,但允许有相同的value(Object)
 59     // 字典的无序的
 60     NSDictionary *dict = @{
 61     @"address" : @"北京",
 62     @"name" : @"jack",
 63     @"name2" : @"jack",
 64     @"name3" : @"jack",
 65     @"qq" : @"7657567765"};
 66     
 67     //    NSArray *keys = [dict allKeys];
 68     //
 69     //    for (int i = 0; i<dict.count; i++)
 70     //    {
 71     //        NSString *key = keys[i];
 72     //        NSString *object = dict[key];
 73     //
 74     //
 75     //        NSLog(@"%@ = %@", key, object);
 76     //    }
 77     
 78     
 79     [dict enumerateKeysAndObjectsUsingBlock:
 80      ^(id key, id obj, BOOL *stop) {
 81          NSLog(@"%@ - %@", key, obj);
 82          
 83          // *stop = YES;
 84      }];
 85 }
 86 
 87 void use3()
 88 {
 89     NSMutableDictionary *dict = @{@"name" : @"jack"};
 90     
 91     
 92     [dict setObject:@"rose" forKey:@"name"];
 93 }
 94 
 95 void use2()
 96 {
 97     NSMutableDictionary *dict = [NSMutableDictionary dictionary];
 98     
 99     // 添加键值对
100     [dict setObject:@"jack" forKey:@"name"];
101     
102     
103     [dict setObject:@"北京" forKey:@"address"];
104     
105     [dict setObject:@"rose" forKey:@"name"];
106     
107     
108     // 移除键值对
109     // [dict removeObjectForKey:<#(id)#>];
110     
111     
112     NSString *str = dict[@"name"];
113     
114     
115     //NSLog(@"%@", str);
116     
117     NSLog(@"%@", dict);
118     
119     
120     //NSLog(@"%@", @[@"jack", @"rose"]);
121 }
122 
123 void use()
124 {
125     /*
126      字典:
127      
128      key ----> value
129      索引 ----> 文字内容
130      
131      里面存储的东西都是键值对
132      
133      
134      */
135     
136     // NSDictionary *dict = [NSDictionary dictionaryWithObject:@"jack" forKey:@"name"];
137     
138     
139     // NSArray *keys = @[@"name", @"address"];
140     // NSArray *objects = @[@"jack", @"北京"];
141     
142     // NSDictionary *dict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
143     
144     
145     /*
146      NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
147      @"jack", @"name",
148      @"北京", @"address",
149      @"32423434", @"qq", nil];*/
150     
151     
152     NSDictionary *dict = @{@"name" : @"jack", @"address" : @"北京"};
153     
154     // id obj = [dict objectForKey:@"name"];
155     
156     id obj = dict[@"name"];
157     
158     NSLog(@"%@", obj);
159     
160     
161     
162     // 返回的是键值对的个数
163     NSLog(@"%ld", dict.count);
164 }

 

  1 //
  2 //  main.m
  3 //  Foundation9-NSDictionary
  4 //
  5 //  Created by mj on 13-4-7.
  6 //  Copyright (c) 2013年 itcast. All rights reserved.
  7 //
  8 
  9 #import <Foundation/Foundation.h>
 10 #import "Student.h"
 11 
 12 #pragma mark 字典的初始化
 13 void dictCreate() {
 14     // NSDictionary是不可变的
 15     NSDictionary *dict = [NSDictionary dictionaryWithObject:@"v" forKey:@"k"];
 16     
 17     // 最常用的初始化方式
 18     dict = [NSDictionary dictionaryWithObjectsAndKeys:
 19             @"v1", @"k1",
 20             @"v2", @"k2",
 21             @"v3", @"k3", nil];
 22     
 23     NSArray *objects = [NSArray arrayWithObjects:@"v1", @"v2", @"v3", nil];
 24     NSArray *keys = [NSArray arrayWithObjects:@"k1", @"k2", @"k3", nil];
 25     dict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
 26     NSLog(@"%@", dict);
 27 }
 28 
 29 #pragma mark 字典的基本用法
 30 void dictUse() {
 31     NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
 32             @"v1", @"k1",
 33             @"v2", @"k2",
 34             @"v3", @"k3", nil];
 35     
 36     // count是计算有多少个键值对(key-value)
 37     NSLog(@"count=%zi", dict.count);
 38     
 39     // 由于NSDictionary是不可变的,所以只能取值,而不能修改值
 40     id obj = [dict objectForKey:@"k2"];
 41     NSLog(@"obj=%@", obj);
 42     
 43     // 将字典写入文件中
 44     NSString *path = @"/Users/apple/Desktop/dict.xml";
 45     [dict writeToFile:path atomically:YES];
 46     
 47     // 从文件中读取内容
 48     dict = [NSDictionary dictionaryWithContentsOfFile:path];
 49     NSLog(@"dict=%@", dict);
 50 }
 51 
 52 #pragma mark 字典的用法
 53 void dictUse2() {
 54     NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
 55                           @"v1", @"k1",
 56                           @"v2", @"k2",
 57                           @"v3", @"k3", nil];
 58     // 返回所有的key
 59     NSArray *keys = [dict allKeys];
 60     //NSLog(@"keys=%@", keys);
 61     
 62     NSArray *objects = [dict allValues];
 63     //NSLog(@"objects=%@", objects);
 64     
 65     // 根据多个key取出对应的多个value
 66     // 当key找不到对应的value时,用marker参数值代替
 67     objects = [dict objectsForKeys:[NSArray arrayWithObjects:@"k1", @"k2", @"k4", nil] notFoundMarker:@"not-found"];
 68     NSLog(@"objects=%@", objects);
 69 }
 70 
 71 #pragma mark 遍历字典
 72 void dictFor() {
 73     NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
 74                           @"v1", @"k1",
 75                           @"v2", @"k2",
 76                           @"v3", @"k3", nil];
 77     // 遍历字典的所有key
 78     for (id key in dict) {
 79         id value = [dict objectForKey:key];
 80         NSLog(@"%@=%@", key, value);
 81     }
 82 }
 83 
 84 #pragma mark 遍历字典2
 85 void dictFor2() {
 86     NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
 87                           @"v1", @"k1",
 88                           @"v2", @"k2",
 89                           @"v3", @"k3", nil];
 90     // key迭代器
 91     NSEnumerator *enumer = [dict keyEnumerator];
 92     id key = nil;
 93     while ( key = [enumer nextObject]) {
 94         id value = [dict objectForKey:key];
 95         NSLog(@"%@=%@", key, value);
 96     }
 97     
 98     // 对象迭代器
 99     // [dict objectEnumerator];
100 }
101 
102 #pragma mark 遍历字典3
103 void dictFor3() {
104     NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
105                           @"v1", @"k1",
106                           @"v2", @"k2",
107                           @"v3", @"k3", nil];
108     [dict enumerateKeysAndObjectsUsingBlock:
109      ^(id key, id obj, BOOL *stop) {
110         NSLog(@"%@=%@", key, obj);
111     }];
112 }
113 
114 #pragma mark 
115 void dictMemory() {
116     Student *stu1 = [Student studentWithName:@"stu1"];
117     Student *stu2 = [Student studentWithName:@"stu2"];
118     Student *stu3 = [Student studentWithName:@"stu3"];
119     
120     // 一个对象称为字典的key或者value时,会做一次retain操作,也就是计数器会+1
121     NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
122                           stu1, @"k1",
123                           stu2, @"k2",
124                           stu3, @"k3", nil];
125     
126     // 当字典被销毁时,里面的所有key和value都会做一次release操作,也就是计数器会-1
127 }
128 
129 int main(int argc, const char * argv[])
130 {
131     @autoreleasepool {
132         dictMemory();
133     }
134     return 0;
135 }

 

 

4、NSNumber

 

//
//  main.m
//  Foundation11-NSNumber
//
//  Created by mj on 13-4-7.
//  Copyright (c) 2013年 itcast. All rights reserved.
//

#import <Foundation/Foundation.h>

void number() {
    // 将int类型的10 包装成 一个NSNumber对象
    NSNumber *number = [NSNumber numberWithInt:10];
    NSLog(@"number=%@", number);
    
    NSMutableArray *array = [NSMutableArray array];
    // 添加数值到数组中
    [array addObject:number];
    
    // 取出来还是一个NSNumber对象,不支持自动解包(也就是不会自动转化为int类型)
    NSNumber *number1 = [array lastObject];
    // 将NSNumber转化成int类型
    int num = [number1 intValue];
    NSLog(@"num=%i", num);
}

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        number();
    }
    return 0;
}

 

 

 

 1 //
 2 //  main.m
 3 //  07-NSNumber
 4 //
 5 //  Created by apple on 13-8-12.
 6 //  Copyright (c) 2013年 itcast. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 
11 int main()
12 {
13     // @20  将 20包装成一个NSNumber对像
14     
15     
16     NSArray *array = @[
17     
18     @{@"name" : @"jack", @"age" : @20},
19     
20     @{@"name" : @"rose", @"age" : @25},
21     
22     @{@"name" : @"jim", @"age" : @27}
23     ];
24     
25     
26     // 将各种基本数据类型包装成NSNumber对象
27     @10.5;
28     @YES;
29     @'A'; // NSNumber对象
30     
31     @"A"; // NSString对象
32     
33     
34     
35     // 将age变量包装成NSNumber对象
36     int age = 100;
37     @(age);
38     //[NSNumber numberWithInt:age];
39     
40     
41     NSNumber *n = [NSNumber numberWithDouble:10.5];
42     
43     
44     int d = [n doubleValue];
45     
46     
47     
48     int a = 20;
49     
50     // @"20"
51     NSString *str = [NSString stringWithFormat:@"%d", a];
52     NSLog(@"%d", [str intValue]);
53     
54     return 0;
55 }
56 
57 void test()
58 {
59     NSNumber *num = [NSNumber numberWithInt:10];
60     
61     NSDictionary *dict =  @{
62     @"name" : @"jack",
63     
64     
65     @"age" : num
66     
67     };
68     
69     NSNumber *num2 = dict[@"age"];
70     
71     
72     int a = [num2 intValue];
73     
74     NSLog(@"%d" , a);
75 }

 

 

5、NSDate

 

 1 //
 2 //  main.m
 3 //  Foundation14-NSDate
 4 //
 5 //  Created by mj on 13-4-7.
 6 //  Copyright (c) 2013年 itcast. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 
11 #pragma mark 日期创建
12 void dateCreate() {
13     // date方法返回的就是当前时间(now)
14     NSDate *date = [NSDate date];
15     
16    // now:  11:12:40
17    // date: 11:12:50
18     date = [NSDate dateWithTimeIntervalSinceNow:10];
19     
20     // 从1970-1-1 00:00:00开始
21     date = [NSDate dateWithTimeIntervalSince1970:10];
22     
23     // 随机返回一个比较遥远的未来时间
24     date = [NSDate distantFuture];
25     
26     // 随机返回一个比较遥远的过去时间
27     date = [NSDate distantPast];
28     NSLog(@"%@", date);
29 }
30 
31 void dateUse() {
32     NSDate *date = [NSDate date];
33     // 返回1970-1-1开始走过的毫秒数
34     NSTimeInterval interval = [date timeIntervalSince1970];
35     
36     // 跟其他时间进行对比
37     // [date timeIntervalSinceDate:<#(NSDate *)#>];
38     NSDate *date2 = [NSDate date];
39     // 返回比较早的那个时间
40     [date earlierDate:date2];
41     // 返回比较晚的那个时间
42     [date laterDate:date2];
43 }
44 
45 void dateFormat() {
46     NSDate *date = [NSDate date];
47     
48     // 2013-04-07 11:14:45
49     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
50     // HH是24进制,hh是12进制
51     formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
52     
53     // formatter.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"] autorelease];
54     
55     NSString *string = [formatter stringFromDate:date];
56     NSLog(@"%@", string);
57     
58     // 返回的格林治时间
59     NSDate *date2 = [formatter dateFromString:@"2010-09-09 13:14:56"];
60     
61     NSLog(@"%@", date2);
62     
63     [formatter release];
64 }
65 
66 int main(int argc, const char * argv[])
67 {
68 
69     @autoreleasepool {
70         dateFormat();
71     }
72     return 0;
73 }

 

 1 //
 2 //  main.m
 3 //  08-NSDate
 4 //
 5 //  Created by apple on 13-8-12.
 6 //  Copyright (c) 2013年 itcast. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 
11 int main()
12 {
13     // 09/10/2011
14     NSString *time = @"2011/09/10 18:56";
15     
16     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
17     formatter.dateFormat = @"yyyy/MM/dd HH:mm";
18     
19     NSDate *date = [formatter dateFromString:time];
20     NSLog(@"%@", date);
21     return 0;
22 }
23 
24 
25 void date2string()
26 {
27     NSDate *date = [NSDate date];
28     
29     
30     // 日期格式化类
31     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
32     
33     // y 年  M 月  d 日
34     // m 分 s 秒  H (24)时  h(12)时
35     formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
36     
37     NSString *str = [formatter stringFromDate:date];
38     
39     NSLog(@"%@", str);
40 }
41 
42 void use()
43 {
44     // 创建一个时间对象
45     NSDate *date = [NSDate date];
46     // 打印出的时候是0时区的时间(北京-东8区)
47     NSLog(@"%@", date);
48     
49     NSDate *date2 = [NSDate dateWithTimeInterval:5 sinceDate:date];
50     
51     
52     // 从1970开始走过的秒数
53     NSTimeInterval seconds = [date2 timeIntervalSince1970];
54     
55     // [date2 timeIntervalSinceNow];
56 }

 

6、NSValue

 1 //
 2 //  main.m
 3 //  08-NSValue
 4 //
 5 //  Created by apple on 13-8-12.
 6 //  Copyright (c) 2013年 itcast. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 
11 
12 // NSNumber之所以能包装基本数据类型为对象,是因为继承了NSValue
13 
14 int main()
15 {
16     
17     // 结构体--->OC对象
18     
19     CGPoint p = CGPointMake(10, 10);
20     // 将结构体转为Value对象
21     NSValue *value = [NSValue valueWithPoint:p];
22     
23     // 将value转为对应的结构体
24     // [value pointValue];
25     
26     NSArray *array = @[value ];
27     
28     
29         // insert code here...
30     // NSLog(@"这是哥修改过的东西6");
31     return 0;
32 }

 

 

 

 

 

posted @ 2014-12-13 11:56  巅峰之斗  阅读(1379)  评论(0编辑  收藏  举报