我一直在阅读大量关于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