在许多代码示例中,也在Apple文档网站上,您将看到这种模式.UIAlertView按顺序调用"show"和"release".
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Panic!"
message:@"The world is gonna explode!"
delegate:nil cancelButtonTitle:@"Who cares?"
otherButtonTitles:@"Boom!", nil];
[alert show];
[alert release];
NSLog(@"released!");
Run Code Online (Sandbox Code Playgroud)
当您运行此代码时,"已发布!" 当UIAlertView框仍在屏幕上时,将显示日志行.当它仍然在屏幕上看到时,释放这个对象似乎是一种奇怪的模式.这背后的想法是什么,这不是针对内存管理的常见问题吗?如果这个"show"调用会阻塞,我可以看到这个模式如何安全地释放内存.但是,由于执行了NSLog方法,它会继续执行您的代码.
代码构建一个警告并生成预期输出"Hello,World!"
示例文件"TestClass.h"
#import <Cocoa/Cocoa.h>
@interface TestClass : NSObject {
}
- (void)foobar;
@end
Run Code Online (Sandbox Code Playgroud)
示例文件"TestClass.m"
#import "TestClass.h"
@implementation TestClass
- (void)say {
// Compiler output "warning: 'TestClass' may not respond to '-hello'"
[self hello];
}
- (void)hello {
NSLog(@"Hello, World!");
}
- (void)foobar {
[self say];
}
@end
@interface TestClass ()
- (void)say;
- (void)hello;
@end
Run Code Online (Sandbox Code Playgroud)
通过在@implementation部分中将"hello"方法置于"say"之上,可以避免编译器警告.但是依赖于你的方法的顺序是令人讨厌的.有没有办法绕过这个编译器警告,而不必按任何特定的顺序放置你的方法?