【问题标题】:Going Crazy with UITextField Input in a Very Simple App在一个非常简单的应用程序中使用 UITextField 输入变得疯狂
【发布时间】:2011-08-10 15:40:16
【问题描述】:

我有一个使用以下代码触发的 PromoCodeViewController:

@implementation Demo_WebServiceCallingUsingiOSAppDelegate

@synthesize window = _window,promoCodeController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    self.promoCodeController = [[PromoCodeViewController alloc] init]; 

    [self.window addSubview:self.promoCodeController.view]; 

    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

PromoCodeViewController 包含 UITextField,我为 PromoCodeViewController 实现 UITextFieldDelegate,如下所示:

@interface PromoCodeViewController : UIViewController<UITextFieldDelegate>

{
    IBOutlet UITextField *promoCodeTextField; 
}

@property (nonatomic,retain) IBOutlet UITextField *promoCodeTextField; 

@end

我实现了textFieldShouldReturn方法如图:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return TRUE; 
}

我什至将 PromoCodeViewController 设置为 UITextField 事件的委托。当我开始在文本框中输入时,它会抛出“程序接收到的信号。EXC_BAD_ACCESS”。当我在 UITextField 中键入第二个字符时会发生这种情况。我做错了什么?

更新1:

错误出现在以下部分:

int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([Demo_WebServiceCallingUsingiOSAppDelegate class]));
    }
}

【问题讨论】:

  • 我认为您不应该在第一个代码块中将窗口设置为 promoCodeViewController ... 虽然我认为这不是导致您的错误的原因。
  • 崩溃时的堆栈跟踪是什么?
  • @sergio 堆栈跟踪中没有任何内容!
  • 见我的answer here。我曾经遇到过同样的问题,它似乎与模拟器 SDK 中的错误有关。
  • 据我所知,EXC_BAD_ACCESS 错误是由于尝试访问不再存在的内容、IE 保留不足或提前发布造成的。看起来您发布的代码没有类似的错误,所以它必须在其他地方。您是否检测到在代码中的任何位置输入的文本?尝试为自己放置一些断点或 NSLog 消息,然后发布结果。

标签: objective-c ios4


【解决方案1】:

您似乎缺少promoCodeTextField 属性的@synthesize 语句。将以下内容添加到您的 Demo_WebServiceCallingUsingiOSAppDelegate 类中(顺便说一下,这可能会受益于重命名):

@synthesize promoCodeTextField = _promoCodeTextField;

如果没有@synthesize 语句,Xcode 的 Nib 文件编辑器将直接设置实例变量而不是调用访问器方法(因为它们不存在);因此,文本字段永远不会保留。

【讨论】:

  • 我已经合成了!是模拟器的BUG!
  • 您发布的代码中没有@synthesize 声明promoCodeTextField
  • promoCodeTextField 确实没有合成。然而,这不是问题所在。首先,出口直接在实例变量上声明,因此 nib 加载机制将使用setValue:forKey:,如果没有设置器,它可以回退到直接访问变量。在这种情况下,documentation 声明该值将被保留。即使不是这种情况,包含视图也会保留文本字段。
【解决方案2】:

文本字段的委托是什么对象?对象通常不保留它们的委托(因为委托经常保留对对象的引用,并且保留周期会导致内存泄漏)。

我的直觉是,您的文本字段的委托已定义并附加在您的笔尖中,但并未保留在任何地方,因此在加载笔尖后不久,委托就被解除分配。一旦文本字段尝试对委托执行任何操作,它就会崩溃。

如果是这样,请确保某些东西(通常是应用程序委托)保留对充当文本字段委托的任何对象的引用。

【讨论】:

    猜你喜欢
    • 2021-02-13
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 2016-01-30
    • 2017-06-19
    • 2013-08-26
    • 1970-01-01
    相关资源
    最近更新 更多