我正在使用 Objective-C 尝试编写一个 iphone 应用程序。
背景:有一个导航控制器管理我的视图控制器。我在 viewDidLoad 上的 FirstLevelViewController 创建了几个 SecondLevelViewController 对象,将它们存储在一个数组中,然后在推送各种表格单元格时加载它们。此外,在 viewDidLoad 上,我的 FirstLevelViewController 在类的实例中创建以保存有关该对象的变量。该类可能有多个实例,因此我不希望创建单例。
各种视图控制器想要向数据对象发送消息。我怎么做?firstlevelviewcontroller 可以向它发送消息,因为它至少创建了第一个。二级视图控制器的行为就像他们不知道数据对象存在一样。
我知道它的基本原理。我知道关于生命、宇宙和一切的意义的知识有很多。是应答应用程序委托吗?不是以单例数据存储方式,而是作为类之间的消息传递方式?我需要参考或指针吗?
我真的很感激帮助。我已经为此失眠了一个星期,并且失去了我的弹珠。谢谢你。
一级视图控制器
#import <Foundation/Foundation.h>
@interface FirstLevelViewController : UITableViewController
<UITableViewDataSource, UITableViewDelegate> {
NSArray *controllers;
}
@property (nonatomic, retain) NSArray *controllers;
@end
#import "FirstLevelViewController.h"
#import "BirthDay.h"
#import "Height.h"
#import "Model.h"
@implementation FirstLevelViewController
@synthesize controllers;
-(void)viewDidLoad {
NSMutableArray *array = [[NSMutableArray alloc]init];
Model *frank = [[Model alloc]init];
frank.date = @"Oh No You Didn't";
self.title = [frank date];
BirthDay *birthday = [[BirthDay alloc]initWithNibName:@"Birthday" bundle:nil];
birthday.title = @"Birth Date";
[array addObject:birthday];
[birthday release];
Height *height = [[Height alloc]initWithNibName:@"Height" bundle:nil];
height.title = @"Height";
[array addObject:height];
[height release];
self.controllers = array;
ModelClass(数据类)
#import <Foundation/Foundation.h>
#import "FirstLevelViewController.h"
#import "BirthDay.h"
#import "model.h"
@interface Model : NSObject {
NSString *date;
}
@property (nonatomic, retain) NSString *date;
@end
#import "Model.h"
@implementation Model
@synthesize date;
@end
SecondLevelViewController
@interface BirthDay : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>{
UILabel *dateLabel;
UIPickerView *datePicker;
}
@property (nonatomic, retain) IBOutlet UILabel *dateLabel;
@property (nonatomic, retain) IBOutlet UIPickerView *datePicker;
@end
#import "BirthDay.h"
#import "FirstLevelViewController.h"
#import "Model.h"
@implementation BirthDay
@synthesize datePicker;
@synthesize dateLabel;
-(IBAction)updateLabel {
NSDate *dateOfBirth = [datePicker date];
NSDate *todaysDate = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:dateOfBirth toDate:todaysDate options:0];
NSInteger months = [components month];
NSInteger days = [components day];
float Months = months;
if (days > 14) {
Months = Months + 0.5;
}
NSString *message = [[NSString alloc]initWithFormat: @"%.1f Months and %d Days old", Months, days];
dateLabel.text = message;
}
@end
(基本上,我希望在调用时更新标签不仅更新标签,还更新名为 frank 的对象。)