lonelysoul

Happy share, happy life.

导航

Objective-C语法简化

NSNumber类型

老写法:

    NSNumber *number;
    number = [NSNumber numberWithChar:'X'];
    number = [NSNumber numberWithInt:12345];
    number = [NSNumber numberWithUnsignedLong:12345ul];
    number = [NSNumber numberWithLongLong:12345ll];
    number = [NSNumber numberWithFloat:123.45f];
    number = [NSNumber numberWithDouble:123.45];
    number = [NSNumber numberWithBool:YES];

新写法:

    NSNumber *number;
    number = @'X';
    number = @12345;
    number = @12345ul;
    number = @12345ll;
    number = @123.45f;
    number = @123.45;
    number = @YES;

 

NSArray类型

老写法:

    NSArray *array = [NSArray arrayWithObjects:@"object1", @"object2", @"object3", nil];

新写法:

NSArray *array = @[ @"object1", @"object2", @"object3" ];  

NSDictonary类型

老写法:

    NSDictionary *dict = [NSDictionary dictionaryWithObjects:@[@"value1", @"value2", @"value3"]
                                       forKeys:@[@"key1", @"key2", @"key3"]];

新写法:

    NSDictionary *dict = @{@"key1": @"value1",@"key2": @"value2",@"key3": @"value3" };

 

快速通过下标定位对象

    NSArray *array =@[ @"object1", @"object2", @"object3" ];

    id obj = array[0]; //通过下标方式获取数组对象,替换原有写法:array objectAtIndex:i];
    NSString *obj1  = @"oooo";
    array[0]  = obj1; //也可以直接为数组对象赋值。替换原有写法:[array replaceObjectAtIndex:i withObject:newObj];
    
    NSDictionary *dict = @{@"key1": @"value1",@"key2": @"value2",@"key3": @"value3" };
    id obj2 = dict[@"key1"];//获取o2对象,替换原有写法:[dic objectForKey:k2];
    dict[@"key2"] = obj;  //重新为键为k2的对象赋值,替换原有写法:[dic setObject:newObj forKey:k2]

 

 

祝您开心愉快 ^_^

posted on 2014-02-25 18:27  lonelysoul  阅读(202)  评论(0编辑  收藏  举报