Aco*_*r83 0 syntax objective-c
假设我已经在Objective-C中创建了一个Fraction类(如"使用Objective-C编程"一书).其中一个方法是添加:,首先创建如下:
//Fraction.h & most of Fraction.m left out for brevity's sake.
-(Fraction *)add: (Fraction*) f {
Fraction *result = [[Fraction alloc] init];
//Notice the dot-notation for the f-Fraction
result.numerator = numerator * f.denominator + denominator * f.numerator;
result.denominator = denominator * f.denominator;
return result;
}
Run Code Online (Sandbox Code Playgroud)
然后在后面的一个练习中,它将返回类型和参数类型更改为id并使其工作.点符号,如上所示不再起作用,所以我改为:
-(id)add: (id)f {
Fraction *result = [[Fraction alloc] init];
result.numerator = numerator * [f denominator] + denominator * [f numerator];
// So forth and so on...
return result;
}
Run Code Online (Sandbox Code Playgroud)
现在我想为什么点符号需要改变是因为直到运行时,程序不知道传递给add参数(f)的对象是什么类型,因此编译器不知道f的任何访问方法.
我能接近理解这个吗?如果没有,有人可以澄清一下吗?
点语法和属性实际上彼此无关,除非它们是同时引入的.
属性可以方便地定义类的访问器,同时还可以添加指定原子性策略和/或内存管理策略的功能.
Dot语法可以方便地访问对象上任何类似访问器的API.点不限于与属性一起使用; 你可以说myArray.length,例如.
在创建点语法时,希望尽可能地限制歧义.因此,特别选择使用点将要求表达式中的对象将被明确键入; id不允许使用泛型类型.
动机是键值编码类型表达式在各种程序中被炸毁的次数.由于点是一种编译的KVC表达式,目标是消除这种脆弱性.
通常,id应避免使用该类型.通过引入instancetype关键词进一步鼓励这一点(与原始问题完全无关,但与上述讨论相关).