我正在尝试一些 iPhone 编程,我遇到了一些对退伍军人来说可能相当明显的事情,但我不确定它为什么会发生。我有两个 UIViewController 类,我想从另一个类访问一个方法。我在 IB 中有两个 NSObject 类与它们相关联(每个类的文件作为 UpdateClass),我正在尝试创建一个类并调用一个方法。看起来很简单,但问题是它正在调用该方法(根据 NSLog),但它没有更新标签。这是我的代码:
//UpdateClass.h
#import <Foundation/Foundation.h>
@interface UpdateClass : NSObject {
IBOutlet UILabel *lbl1;
IBOutlet UILabel *lbl2;
}
@property (nonatomic, retain) IBOutlet UILabel *lbl1;
@property (nonatomic, retain) IBOutlet UILabel *lbl2;
- (void)updateLabels;
@end
//UpdateClass.m
#import "UpdateClass.h"
@implementation UpdateClass
@synthesize lbl1;
@synthesize lbl2;
- (void)updateLabels {
NSString *someWord = @"Whatever"; // This could be anything
NSLog(@"NSObject Update");
[lbl1 setText:someWord];
[lbl2 setText:someWord];
}
@end
//ViewController1.h
#import <UIKit/UIKit.h>
@class UpdateClass;
@interface ViewController1 : UIViewController {
IBOutlet UIButton *button1;
NSObject *UpdateClassObject;
UpdateClass *updateClass;
}
@property (nonatomic, retain) IBOutlet UIButton *button1;
@property (nonatomic, retain) NSObject *UpdateClassObject;
@property (nonatomic, retain) UpdateClass *updateClass;
- (void)updateLabels:(id)sender;
@end
//ViewController1.m
#import "ViewController1.h"
#import "UpdateClass.h"
@implementation ViewController1
@synthesize button1;
@synthesize UpdateClassObject;
@synthesize updateClass;
- (void)viewDidLoad {
[super viewDidLoad];
updateClass = [[UpdateClass alloc] init];
}
- (void)updateLabels:(id)sender; { //This is connected to TouchDown on button1
NSLog(@"Calls UpdateLabels");
[updateClass updateLabels]; //Calls the class method
}
//ViewController2.h
#import <UIKit/UIKit.h>
@class UpdateClass;
@interface ViewController2 : UIViewController {
IBOutlet UIButton *button2;
NSObject *UpdateClassObject;
UpdateClass *updateClass;
}
@property (nonatomic, retain) IBOutlet UIButton *button2;
- (void)updateLabels:(id)sender;
@end
//ViewController2.m
#import "ViewController2.h"
#import "UpdateClass.h"
@implementation ViewController2
@synthesize button2;
@synthesize UpdateClassObject;
@synthesize updateClass;
- (void)viewDidLoad {
[super viewDidLoad];
updateClass = [[UpdateClass alloc] init];
}
- (void)updateLabels:(id)sender; { //This is connected to TouchDown on button2
NSLog(@"Calls UpdateLabels");
[updateClass updateLabels]; //Calls the class method
}
因此,IB 中为两个视图都连接了一个 NSObject。每个视图上都有一个连接到 NSObject 和文件所有者的标签(可能不需要将它们连接到两者)。当按下按钮时(在 IB 中也正确连接),标签应该变成一些字符串。NSLog 报告方法被调用,但标签没有改变。这里有什么问题?
(注意:可能会有一些小错误,因为我现在没有所有的代码,所以我不得不输入其中的一些)。