這次我將程式分開成兩個class來寫 順便練習怎麼各自呼叫對方的method 另外我這次設計了兩個xib 當一開始classA的xib載入後 我按下按鈕之後 程式能切換到class B的xib
test12ViewController.h
// forward declaration@class Testcontroller;
@interface test12ViewController : UIViewController {
//另外一個class Testcontroller *testcontroller;
}
//以下這樣寫 就可以使用dot syntax@property(nonatomic,retain)Testcontroller *testcontroller;
//用來切換不同的view-(IBAction)change:(id)sender;
-(int)display;
@end
test12ViewController.m
#import " test12ViewController.h "
//用Testcontroller產生一個instance object#import " Testcontroller.h "
@implementation test12ViewController
@synthesize testcontroller;
-(IBAction)change:(id)sender
{
if (self.testcontroller==nil) {
//載入Testcontroller的xib Testcontroller *testcontrollertemp=[[Testcontroller alloc]initWithNibName:@"Testcontroller" bundle:nil];
self.testcontroller=testcontrollertemp;
[testcontrollertemp release];
//加到原本的view上面 [self.view addSubview:testcontroller.view];
}
}
-(int)display
{
int x=5;
return x;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[testcontroller release];
[super dealloc];
}
@end
testcontroller.m
#import " Testcontroller.h "
//必須記得import以下 因為要產生test12ViewController的instance//若沒有加入這段 會出現 "XXX may not respond to class"#import " test12ViewController.h "
@implementation Testcontroller
@synthesize display;
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(IBAction)test:(id)sender
{
int y;
//產生test12ViewController的instance test12ViewController *integer=[[test12ViewController alloc]init];
//透過這個instance 去呼叫test12ViewController的method y=[integer display];
//將int轉換成字串 NSString *dispalytext=[[NSString alloc]initWithFormat:@"%d",y];
display.text=dispalytext;
[integer release];
[dispalytext release];
}
- (void)dealloc {
[super dealloc];
}
@end