我一直在閱讀大量關於iPhone開發和書中示例的書籍,但我注意到MVC的想法並沒有真正被正確教授(儘管作者確實說Xcode「本身「到MVC的編碼方式)。Xcode開發模型 - 視圖 - 控制器(MVC)問題
一個簡單的例子。我想製作一個簡單的計算器應用程序(許多人開始這樣做)。
我有我的所有代碼在xxxxxViewController.m文件內的工作版本。行動和奧特萊斯運作良好。這種方法的麻煩是如果我想有多個視圖(普通計算器和科學計算器)我會複製並粘貼我的代碼,所以我現在有兩個版本。我清楚地試圖避免這種情況。
所以,我創建了我自己的類(基於NSObject)作爲我的CalculatorEngine。
問題是當試圖分配和初始化我的CalculatorEngine我收到錯誤,如「用不同類型重新定義CalculatorEngine」和「缺少類型說明符,默認爲int」。
我想我錯過了一些明顯的東西。
你能指點我一個單獨的類被用作「引擎」而不是在xxxxViewController中的代碼的任何類型的樣本的方向嗎?
此時下面的代碼實際上沒有做任何事情。我只是想在CalculatorViewController.m中使用CalculatorEngine對象。這是我收到錯誤的地方。
// CalculatorAppDelegate.h
// Calculator
#import <UIKit/UIKit.h>
@class CalculatorViewController, CalculatorEngine;
@interface CalculatorAppDelegate : NSObject <UIApplicationDelegate>
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet CalculatorViewController *viewController;
@end
// CalculatorAppDelegate.m
// Calculator
#import "CalculatorAppDelegate.h"
#import "CalculatorViewController.h"
@implementation CalculatorAppDelegate
@synthesize window = _window;
@synthesize viewController = _viewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
}
- (void)applicationWillResignActive:(UIApplication *)application
{
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
}
- (void)applicationWillTerminate:(UIApplication *)application
{
}
- (void)dealloc
{
}
@end
// CalculatorViewController.h
// Calculator
#import <UIKit/UIKit.h>
@interface CalculatorViewController : UIViewController
@end
// CalculatorViewController.m
// Calculator
#import "CalculatorViewController.h"
#import "CalculatorEngine.h"
@implementation CalculatorViewController
// This was wrong here. Now moved to viewDidLoad().
//CalculatorEngine *CalcEng;
//CalcEng = [[CalculatorEngine alloc] init];
// trouble here. CalcEng is unknow.
-(IBAction)buttonPressed:(id)sender {
[CalcEng setRegisterX:1];
}
- (void)viewDidLoad
{
CalculatorEngine *CalcEng;
CalcEng = [[CalculatorEngine alloc] init];
[super viewDidLoad]
}
- (void)didReceiveMemoryWarning
{
}
- (void)viewDidUnload
{
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
}
@end
// CalculatorEngine.h
// Calculator
#import <Foundation/Foundation.h>
@interface CalculatorEngine : NSObject
@end
// CalculatorEngine.m
// Calculator
#import "CalculatorEngine.h"
@implementation CalculatorEngine
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
@end
這是一個Objective-C問題。這不是iPhone特有的。 「缺少類型說明符,默認爲int」的部分聽起來像是缺少包含。發佈你的代碼,或者至少是一個框架(在方法內部留下代碼)。 –
示例代碼現已包含在原始文章中。 – David