【问题标题】:@synthesize is not working and basic operations are not working in Objective-C@synthesize 不起作用,基本操作在 Objective-C 中不起作用
【发布时间】:2010-12-12 11:55:03
【问题描述】:

我不确定为什么这段代码不起作用。当我单击一个按钮(操作:buttonclick)时,它应该将两个文本框(MyTextLabel 和 MyTextLabel2)的文本增量值“r”加一。代码如下:

MainView.h

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

@interface MainView : UIView {
    IBOutlet UIButton *MyButton;
    IBOutlet UILabel *MyTextLabel;
    IBOutlet UILabel *MyTextLabel2;
}

@property (nonatomic, retain) UIButton *MyButton;
@property (nonatomic, retain) UILabel *MyTextLabel;
@property (nonatomic, retain) UILabel *MyTextLabel2;


- (IBAction)buttonclick;
@end

MainView.m:

#import "MainView.h"
#include <stdlib.h>
#include <libc.h>

@implementation MainView

@synthesize MyButton, MyTextLabel, MyTextLabel2;

int r;

- (IBAction)buttonclick {
    r++
    if(r < 50) {
        MyTextLabel.text = @"< 50";
    }
    else {
        MyTextLabel2.text = @"=> 50";
    }
}
@end

【问题讨论】:

    标签: objective-c text integer label synthesizer


    【解决方案1】:

    Action 方法总是有一个 sender 参数,所以你的 -buttonClick: 方法应该这样声明:

    -(IBAction) buttonClick: (id)sender {
    }
    

    【讨论】:

      【解决方案2】:

      在 Objective-C 中,变量和属性的名称必须以小写字母开头,以符合键值编码 (KVC) 协议(总是 myButton,绝不是 MyButton)。 @synthesize 指令依赖于此来生成 setter 和 getter。因此,对于myButton @synthesize 将生成-(void)setMyButton:(UIButton *)button-(UIButton *)myButton

      所以,请将MyButton 及其同事设为小写,看看是否有帮助。

      【讨论】:

        【解决方案3】:

        我感觉您使用 int r 的方式有问题。尝试将 static int r; 放在 MainView.h 中 @interface 行的顶部,并在 - (IBAction)buttonclick; 行下添加:

        +(void) initialize;
        

        然后从 MainView.m 中删除 int r;。然后在 MainView.m 添加:

        +(void) initialize {
           count = 0;
        }
        

        【讨论】:

        • 或者只是让r成为真正的ivar:将其添加到@interface中声明的变量中,在-init中将其初始化为0,然后在buttonClick中将其递增。
        • 哦,那是另一种方式:)
        • @Sixten Otto:你不需要使用初始化 r。在 alloc 中设置为 0。
        • @Abizern 我只知道有人会跳上去。 :-) 是的,运行时在分配内存时会将 ivars 清零,因此这部分不是绝对必要的。
        • 感谢您的帮助,但现在它在“#import "MainView.h" 行下显示“预期的特殊限定符列表在静态之前”。它还说“r”仍未声明!
        【解决方案4】:

        我看到两个问题:

        1. 你不能在你拥有它的地方声明int r。您应该在界面的变量块(在其中声明按钮和标签或在方法之外)或方法定义中声明它。
        2. 带有 r++ 的行不以分号结尾。

        【讨论】:

          【解决方案5】:

          你没有在你的问题中说究竟是什么没有按照你期望的方式工作。我的猜测是您的插座实际上没有正确连接。您可能希望像这样向buttonClick 添加一条日志语句:

          NSLog(@"button click called! MyTextLabel is %@", MyTextLabel);
          

          主要是要确保它不是nil

          【讨论】:

          • 抱歉,没说清楚!代码在打开应用程序时停止并在代码中停止在“@synthesize”
          • 可以在原问题中添加堆栈跟踪吗?
          猜你喜欢
          • 1970-01-01
          • 2015-10-23
          • 1970-01-01
          • 2022-09-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-20
          • 1970-01-01
          相关资源
          最近更新 更多