【发布时间】:2011-06-25 19:22:36
【问题描述】:
在我的 ViewController 类中实现 UITextFieldDelegate 时,在文本字段中输入第一个字符时会引发以下错误:
-[MyViewController respondsToSelector:]: message sent to deallocated instance...
所以,我尝试创建一个单独的类(仅继承 NSObject)并实现 UITextFieldDelegate。你猜怎么着,效果很好。但是,这引入了一些其他问题,因为我必须做很多我想避免的丑陋的跨类通信。这是我的应用委托代码的相关部分:
@interface RMSAppDelegate : NSObject <UIApplicationDelegate,
UITabBarControllerDelegate>
@property (nonatomic, retain) UIViewController* myViewController;
@end
@implementation MyAppDelegate
@synthesize myViewController;
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
myViewController = [[MyViewController alloc]
initWithNibName:@"MyView" bundle:nil];
[self.window setRootViewController:myViewController];
[self.window makeKeyAndVisible];
return YES;
}
@end
.. 这是正在显示的内容:
@interface MyViewController : UIViewController <UITextFieldDelegate>
@property (nonatomic, retain) IBOutlet UITextField* pinTextField;
- (void)viewDidLoad;
@end
@implementation MyViewController
@synthesize pinTextField;
- (void)viewDidLoad {
// DOES NOT WORK (WHY?)
//[pinTextField setDelegate:self];
// WORKS, BUT I'D LIKE TO AVOID
[pinTextField setDelegate:[[[MyTextFieldDelegate alloc] init] autorelease];
[pinTextField becomeFirstResponder];
[super viewDidLoad];
}
@end
如果您看到任何我可以做得更好的代码(甚至是离题),请发表评论。
【问题讨论】:
-
@albertamg:谢谢,我已将代码修改为示例,但遗漏了一些内容。去掉
dealloc方法,缩短代码,专注问题
标签: objective-c ios cocoa-touch uiviewcontroller uitextfielddelegate