OC-FUNDATION-NSDictionary&NSMutableDictionary&Block

1.NSDictionary

1.1由键值对组成,关键字不允许重复,值可以重复
1.2创建方法

NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:@"one",@"1",@"two",@"2",@"three",@"3", nil];//标准方法

NSDictionary *dict2 = @{@"1":@"one",@"2":@"two",@"3":@"three"};//优化后的方法,最常用

NSArray *object = @[@"one",@"two",@"three"];//存值
NSArray *key = @[@"1",@"2",@"3"];//存关键字
NSDictionary *dict3 = [NSDictionary dictionaryWithObjects:object forKeys:key];//将数组转换成字典

NSDictionary *dict4 = [NSDictionary dictionaryWithDictionary:dict3];//创建dict3的副本

1.3求键值对个数

NSLog(@"%lu",dict3.count);

1.4将字典中的所有值转换成数组

NSArray *object2 = [dict3 allValues];

1.5将字典中的所有关键字转换成数组

NSArray *key2 = [dict3 allKeys];

1.6通过关键字找到对应值

//获取字典中所有值,即将字典转换成数组的方法
NSArray *object2 = [dict3 allValues];
NSArray *key2 = [dict3 allKeys];
NSLog(@"%@",object2);
NSLog(@"%@",key2);
//根据一个关键字查找一个值
NSString *str = [dict3 objectForKey:@"1"];//标准方法
NSLog(@"%@",str);
str = dict3[@"1"];
NSLog(@"%@",str);//优化后的方法,最常用的方法
//根据多个关键字来找多个值
NSArray *key1 = @[@"1",@"4"];
NSArray *obj1 = [dict3 objectsForKeys:key1 notFoundMarker:@"没有对应的值"];
NSLog(@"%@",obj1);
for(NSString *str1 in obj1)
    NSLog(@"%@",str1);

1.7通过值找对应的关键字

NSArray *key3 = [dict3 allKeysForObject:@"three"];

1.8对字典中的值排序

-(NSComparisonResult)compareAge:(SHStudent *)other
{
    NSNumber *selfAge = [NSNumber numberWithInt:self.age];
    NSNumber *otherAge = [NSNumber numberWithInt:other.age];
    return [otherAge compare:selfAge];

}



SHStudent *stu1 = [SHStudent studentWithName:@"zhangsan" andAge:18];
SHStudent *stu2 = [SHStudent studentWithName:@"lisi" andAge:20];
SHStudent *stu3 = [SHStudent studentWithName:@"wangwu" andAge:19];

NSDictionary *stu = @{@"1":stu1,@"2":stu2,@"3":stu3};
NSArray *sortedAge = [stu keysSortedByValueUsingSelector:@selector(compareAge:)];
for(NSString *key in sortedAge)
{
    NSLog(@"%@ = %@",key,stu[key]);
}

1.9遍历

NSEnumerator * e = [dict3 objectEnumerator];//枚举器值遍历
while (str = [e nextObject]) {
    NSLog(@"%@",str);
}
e = [dict3 keyEnumerator];//枚举器关键字遍历
while (str = [e nextObject]) {
    NSLog(@"%@",str);
}
for(NSString *str in dict3)//快速遍历
    NSLog(@"%@ %@",str,dict3[str]);

2.0字典的文件读写

[dict3 writeToFile:@"/Users/tarena/Desktop/dict3.plist" atomically:YES];
        NSDictionary *dict5 = [NSDictionary dictionaryWithContentsOfFile:@"/Users/tarena/Desktop/dict3.plist"];
        NSLog(@"%@",dict5);

2.NSMutableDictionary

2.1可变字典,是NSDictionary的子类
2.2创建方法

NSMutableDictionary *dict1 = [NSMutableDictionary dictionary];
NSMutableDictionary *dict2 = [NSMutableDictionary dictionaryWithCapacity:100];
NSMutableDictionary *dict3 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"one",@"1",@"two",@"2",@"three",@"3", nil];//标准方法
NSMutableDictionary *dict4 = @{@"1":@"one",@"2":@"two",@"3":@"three"};//退化成不可变字典

2.3添加方法

[dict3 setValue:@"four" forKey:@"4"];
NSLog(@"%@",dict3);
NSDictionary *added = @{@"5":@"five",@"6":@"six",@"7":@"seven"};
[dict3 addEntriesFromDictionary:added];//添加多个键值对
NSLog(@"%@",dict3);

2.4覆盖方法

NSDictionary *dict5 = @{@"1":@"one",@"2":@"two",@"3":@"three"};
NSMutableDictionary *dict6 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"aaaaa",@"1",@"bbbb",@"2",@"cccc",@"3", nil];
[dict6 setDictionary:dict5];
NSLog(@"%@",dict6);

2.5删除方法

[dict3 removeObjectForKey:@"1"];//删除指定关键字对应的键值对
NSLog(@"%@",dict3);
NSArray *del = @[@"3",@"5"];
[dict3 removeObjectsForKeys:del];
NSLog(@"%@",dict3);
[dict3 removeAllObjects];
NSLog(@"%lu",dict3.count);

3.Block

3.1是一种新的数据类型
3.2Block类型的变量中存储的是一段儿程序代码
3.3语法

#import <Foundation/Foundation.h>


void fun()
{
    NSLog(@"函数被执行了");
}

void(^myBlock)(void) = ^void(void)
{
    NSLog(@"Block被执行了");
};

double(^myBlock1)(int,int) = ^double(int a,int b)
{
    return a+b;
};

typedef void(^BlockType)(void);

int main(int argc, const char * argv[]) {
    @autoreleasepool {

//        fun();
        myBlock();
        void (*pf)() = fun;
        pf();
        NSLog(@"%lg",myBlock1(5,6));
        BlockType b1;
        b1 = ^void(void)
        {
            NSLog(@"用block类型定义的变量");
        };
        b1();
    }
    return 0;
}

3.4Block与全局变量
3.5Block与局部变量
3.6Block在自定义类中的使用

#import <Foundation/Foundation.h>
#import "SHMyClass.h"

int g_i=0;
void fun()
{
    NSLog(@"函数被执行了");
}

void(^myBlock)(void) = ^void(void)
{
    NSLog(@"Block被执行了");
};

double(^myBlock1)(int,int) = ^double(int a,int b)
{
    return a+b;
};

typedef void(^BlockType)(void);
typedef double(^MyBlock1)(int,int);

void fa(MyBlock1 a)
{
    NSLog(@"%lg",a(3,5));
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {

//        fun();
        myBlock();
        void (*pf)() = fun;
        pf();
        NSLog(@"%lg",myBlock1(5,6));
        BlockType b1;
        b1 = ^void(void)
        {
            NSLog(@"用block类型定义的变量");
        };
        b1();
        MyBlock1 b2 = ^double(int a,int b)
        {
            return a + b;
        };
        NSLog(@"%lg",b2(2,3));

        fa(^double(int a,int b){return a + b;});
        fa(^double(int a,int b){return a * b;});

        MyBlock1 b3 = ^double(int a,int b)
        {
            a *= g_i;//全局变量可以被访问
            g_i = 20;//全局变量可以被赋值
            return a + b;
        };
        NSLog(@"b3 = %lg",b3(2,3));
        NSLog(@"全局变量:%d",g_i);

        int i2= 30;
        __block int i3 = 50;
        BlockType b4 = ^void(void)
        {
            NSLog(@"%d",i2);//局部变量可以在block中被访问
//            i2 = 40;//局部变量不能在block中被赋值
            i3 = 60;//加上关键字__block后,局部变量可以在Block中被赋值

        };
        b4();
        NSLog(@"i3 = %d",i3);

        //Block在自定义类中的使用
        SHMyClass *myc = [[SHMyClass alloc]init];
        [myc method];
        [myc method:^void(void){NSLog(@"没得说了很强");}];
        [myc method:^void(void){NSLog(@"随便说说");}];
        [myc method2:^double(int a,int b){return a+b;}];
        [myc method3:^double(int x,int y)
        {
            return x * y;
        }andX:3 andY:2];

        [myc getBlock]();
        myc.b = ^void(void){NSLog(@"block做属性");};
        myc.b();
    }
    return 0;
}

思考练习

定义一个学生类
1.属性:姓名、年龄
2.方法:初始化、工厂、show
在主函数中,定义5个学生类的对象,分别用数组、字典存放,并用Block排序
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
解析
SHStudent类:

#import <Foundation/Foundation.h>

@interface SHStudent : NSObject
@property NSString *name;
@property int age;
-(id)initWithName:(NSString*)name andAge:(int)age;
+(id)studentWithName:(NSString*)name andAge:(int)age;
-(void)show;
@end
#import "SHStudent.h"

@implementation SHStudent
-(id)initWithName:(NSString *)name andAge:(int)age
{
    if (self = [super init])
    {
        self.name = name;
        self.age = age;
    }
    return self;
}
+(id)studentWithName:(NSString *)name andAge:(int)age
{
    __autoreleasing SHStudent *s = [[SHStudent alloc] initWithName:name andAge:age];
    return s;
}
-(void)show
{
    NSLog(@"姓名:%@,年龄:%d", self.name, self.age);
}
-(NSString *)description
{
    return [NSString stringWithFormat:@"姓名:%@,年龄:%d", self.name, self.age];
}
@end

main函数:

#import <Foundation/Foundation.h>
#import "SHStudent.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        SHStudent *stu1 = [[SHStudent alloc] initWithName:@"张三" andAge:18];
        SHStudent *stu2 = [[SHStudent alloc] initWithName:@"李四" andAge:20];
        SHStudent *stu3 = [[SHStudent alloc] initWithName:@"王五" andAge:19];
        SHStudent *stu4 = [[SHStudent alloc] initWithName:@"赵六" andAge:22];
        SHStudent *stu5 = [[SHStudent alloc] initWithName:@"钱七" andAge:21];

        NSArray *stu = @[stu1, stu2, stu3, stu4, stu5];
        NSArray *sorted = [stu sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            NSNumber *obj1Age = [NSNumber numberWithInt:[obj1 age]];
            NSNumber *obj2Age = [NSNumber numberWithInt:[obj2 age]];
            return [obj1Age compare:obj2Age];
        }];
        for (SHStudent *s in sorted)
        {
            NSLog(@"%@", s);
        }

        NSDictionary *dict = @{@"1":stu1,@"2":stu2,@"3":stu3,@"4":stu4,@"5":stu5};
        sorted = [dict keysSortedByValueUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            NSNumber *obj1Age = [NSNumber numberWithInt:[obj1 age]];
            NSNumber *obj2Age = [NSNumber numberWithInt:[obj2 age]];
            return [obj1Age compare:obj2Age];
        }];
        for (NSString *key in sorted)
        {
            NSLog(@"%@=%@", key, dict[key]);
        }
    }
    return 0;
}
发布了52 篇原创文章 · 获赞 5 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/shuan9999/article/details/52366454