这是一个独立的test.m
文件,我正在用它来测试行为。
编译方法: clang test.m -o test.app -fobjc-arc -ObjC -framework Foundation
。请确保已安装Xcode命令行工具。
#import <Foundation/Foundation.h>
@protocol Protocol
@optional
- (id)objProxyMethod;
@end
@interface ReturnObject: NSObject
@end
@interface Test : NSObject <Protocol>
@end
@interface Proxy : NSObject <Protocol>
- (id)objProxyMethod;
@end
@implementation ReturnObject
- (void)dealloc {
NSLog(@"ERROR:");
NSLog(@"I'm getting deallocated!");
NSLog(@"This shouldn't happen!");
}
- (NSString *)description {
return @"Blank object!";
}
@end
@implementation Proxy
- (id)objProxyMethod {
NSLog(@"in [Proxy objProxyMethod]!");
return [[ReturnObject alloc] init];
}
@end
@implementation Test
- (void)forwardInvocation:(NSInvocation *)invocation {
NSLog(@"Forwarded invocation!");
Proxy *proxy = [[Proxy alloc] init];
[invocation invokeWithTarget: proxy];
NSUInteger length = [[invocation methodSignature] methodReturnLength];
if (length == 8) {
id result;
[invocation getReturnValue:&result];
}
}
@end
int main () {
Test *test = [[Test alloc] init];
id objResult = [test objProxyMethod];
NSLog(@"objResult = \"%@\"", objResult);
return 0;
}
如果我将
[invocation getReturnValue:&result];
注释掉,返回对象就不会被dealloc
。我不知道这是一个错误,还是我误解了NSInvocation
的工作原理。
__weak
而不是__unsafe_unretained
,它还能正常工作吗?到目前为止,当我使用__weak
时没有出现任何错误,但我只是想确认一下。 - ryanrhee__weak
而应该使用__unsafe_unretained
。弱引用变量需要使用objc_storeWeak
运行时函数进行设置,而-[NSInvocation getReturnValue:]
显然不会这样做。 - rob mayoff__weak id result
,编译器会在result
超出作用域时生成对objc_destroyWeak
的调用。由于result
没有使用objc_storeWeak
进行设置,因此行为是未定义的。 - rob mayoff