Objective-C/OC Syntactic sugar/语法糖

Dot syntax / 点语法

快速使用 setter / getter 赋值/获取值

一般情况:

1
2
3
4
getter:    [anObject setKey:Value];    // 给 anObject 发送消息 setKey: ,传入 Value
// 即使用 anObject 的类方法 - (returnValueType)getKey;
setter: [anObject key]; // 给 anObject 发送消息 key
// 即使用 anObject 的类方法 -(void)key:(keyValueType)key;

使用点语法:anObject.key
1
2
setter:    key.value = aNumber;
getter: something = key;

Object Literals

快速赋值替代初始化赋值、构造方法 / 工厂方法 / Factory method pattern

NSString / NSMutableString

1
2
3
4
5
6
7
8
+ (instancetype)string;    // 生成空的字符串
NSString *string = [NSString string];
+ (instancetype)stringWithString; // 工厂方法生成字符串
NSString *strWithStr = [NSString stringWithString:@"There is a string"];
+ (instancetype)initWithString:(NSString *)aString; // 构造方法初始化字符串
NSString *intWithStr = [[NSString alloc] initWithString:@"Init with string"];

NSString *sugarString = @"Is Awesome!"; // 语法糖!


NSArray / NSMutableArray
1
2
3
4
5
6
7
8
+ (instancetype)array;    // 生成空的数组
NSArray *array = [NSArray array];
+ (instancetype)arrayWithObjects:(ObjectType)firstObj, ...; // 工厂方法生成数组
NSArray *arrWithArr = [NSArray arrayWithObjects:@"arrayMember1", @"arrayMember2", @"arrayMember3", @"arrayMember4", nil];
+ (instancetype)initWithArray:(NSArray<ObjectType> *)anArray; // 构造方法初始化数组
NSArray *intWithArr = [[NSArray alloc] initWithArray:@[@"arrayMember1", @"arrayMember2", @"arrayMember3", @"arrayMember4", nil]];

NSArray *sugarArray = @[@"arrayMember1", @"arrayMember2", @"arrayMember3", @"arrayMember4"] // 语法糖!

NSValue / NSMutableValue & NSNumber / NSMutableNumber
1
2
3
4
5
6
7
8
9
10
11
12
- (instancetype)initWithBytes:(const void *)value objCType:(const char *)type;
- (NSValue *)valueWithBytes:(const void *)value objCType:(const char *)type;
NSNumber *num = [NSNumber numberWithInt:42]; // 万物的终点
- (NSValue *)value:(const void *)value withObjCType:(const char *)type;

NSNumber *sugarNumber = @1024; // 语法糖!
NSNumber *UnsignedIntNum = @65536U;
NSNumber *longNum = @111111111L;
NSNumber *longLongNum = @222222222222222;
NSNumber *floatNum = 9.9999999F;
NSNumber *doubleNum = 6.9;
NSNumber *isBOOL = YES;

NSDictionary / NSMutableDictionary
Objective-C 的词典(NSDictory)我觉得最反人类的问题就在于 key 在前 value 在后了, @"value", @"key" 的形式真是让人一头雾水。
1
2
3
4
5
6
7
8
9
10
11
12
NSNumber * number = [NSNumber numberWithInt:1];
NSArray * array = [NSArray arrayWithObjects:@"one", @"two", nil];
NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];

// 一颗赛提!这是最吼的!
NSDictionary *newDictionary = @{@"keyApllo" : @"dic1", @"keyBella" : @"dic2"};
// 或者你有很多对
NSDictionary *dictionary = @{
@"key0" : @"value0",
@"key1" : @"value1",
@"key2" : @"value2"
};

NSNumber *c = @('a');      // think about this? (prompt:ANSI)

使用下标便捷的访问数组元素

1
2
3
// 来自 Stanford CS193p
randomCard = [self.cards objectAtIndex:index]
randomCard = self.cards[index]; // syntacticSugar!