我想使用消息转发让任何未实现的 getter 方法返回 0,而不是抛出无法识别的选择器异常。喜欢
MyClass *r = [[MyClass alloc] init];
NSNumber *n = (NSNumber *)r;
NSLog(@"%d", [n integerValue]); // output 0
NSLog(@"%f", [n doubleValue]); // output 0.00000
NSLog(@"%@", [n stringValue]); // output (null)
所以我写了这个例子:
#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSNumber *n = (NSNumber *)self;
NSLog(@"%d", [n integerValue]);
NSLog(@"%f", [n doubleValue]);
NSLog(@"%@", [n stringValue]);
return YES;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
NSMethodSignature *ms = [super methodSignatureForSelector:aSelector];
if(ms)
return ms;
// Q = uint64_t, so it should also works for double which is also 64bit
return [NSMethodSignature signatureWithObjCTypes:"Q@:"];
}
- (void)forwardInvocation:(NSInvocation *)anInvocation {
uint64_t ZERO64 = 0;
[anInvocation setReturnValue:&ZERO64];
}
真实设备上的输出结果是 0, 0.00000, (null),但在模拟器上是 0, NaN, (null)
所以 double 类型不能按预期工作。我的第一个想法是将 NSMethodSignature 更改为“d@:”(d 是双倍的)
输出结果在设备和模拟器上都是正确的,但只有模拟器上发生了一些奇怪的事情。运行此代码,它将在第 6 次循环中崩溃,并出现某种 CALayer 异常:
#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
for(NSInteger i = 0; i < 100; i++) {
NSInteger t = [(NSNumber *)self integerValue];
UIViewController *view = [[UIViewController alloc] init];
// it always crash on the 6th loop on this line**
UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:view];
}
return YES;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
NSMethodSignature *ms = [super methodSignatureForSelector:aSelector];
if(ms)
return ms;
// we change to return double
return [NSMethodSignature signatureWithObjCTypes:"d@:"];
}
- (void)forwardInvocation:(NSInvocation *)anInvocation {
uint64_t ZERO64 = 0;
[anInvocation setReturnValue:&ZERO64];
}
我很好奇两个问题,为什么在第一个示例中在模拟器上返回 NaN,以及在第二个示例中发生了什么?