【发布时间】:2009-07-24 17:12:37
【问题描述】:
我正在尝试一些 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 报告方法被调用,但标签没有改变。这里有什么问题?
(注意:可能会有一些小错误,因为我现在没有所有代码,所以我不得不输入其中的一些)。
【问题讨论】:
-
我想知道你为什么使用一个类来保存标签并更新它们?还想知道您是否将这些类中的标签添加到您的 UIViewControllers 视图中
-
好吧,因为我认为某种用于处理更新的集中类是有意义的......但也许我不明白 Objective-C 编程应该如何工作。
-
真的不需要,你可以直接在你的 UIViewCOntroller 中处理更新标签,这就是控制器用来管理你的视图的东西
标签: iphone class methods label