开发者

@synthesize is not working and basic operations are not working in Objective-C

I am unsure why this code will not work. When I click a button (action: buttonclick) it should change the two text boxes' (MyTextLabel and MyTextLabel2) text increment value "r" by one. Here is the code:

MainView.h

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

@interface MainView : UIView {
    IBOutlet UIButton *MyButton;
    IBOutlet UILabel *MyTextLabel;
    IBOutlet UILabel *MyTextLabel开发者_高级运维2;
}

@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


I have a feeling something's wrong with the way you're using int r. Try putting static int r; at the top of the @interface line in MainView.h and also add, under the - (IBAction)buttonclick; line:

+(void) initialize;

Then remove int r; from MainView.m. Then in MainView.m add:

+(void) initialize {
   count = 0;
}


I see two issues:

  1. You can't declare int r where you have it. You should declare it in your interface's variable block (where you declare your button and labels or outside a method) or in the method definition.
  2. The line with r++ isn't ended with a semi-colon.


You don't say in your question what, exactly, isn't working the way you expect it. My guess is going to be that your outlets aren't actually connected properly. You might want to add a log statement to buttonClick like this:

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

The point being, mostly, to be sure it isn't nil.


In Objective-C the names of variables and properties must start with a lowercase letter to conform to the Key-Value Coding (KVC) protocol (always myButton, never MyButton). The @synthesize directive relies on this to generate the setters and getters. Thus, for myButton @synthesize will generate -(void)setMyButton:(UIButton *)button and -(UIButton *)myButton.

So, do make MyButton and its colleagues lowercase and see if it helps.


Action methods always have a sender argument, so your -buttonClick: method should be declared like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜