我正在使用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;
#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
@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的对象。)
答案 0 :(得分:1)
您可以从SecondLevelViewController发送通知等。然后,数据对象或FirstLevelViewController可以注册此类通知并根据需要进行处理。