下面是一个简单示例,说明我如何从 plist 中读取数据并在 TableView 中显示数据。如果我要使用一个对象来表示我的模型,我会怎么做?
@interface RootViewController : UITableViewController {
NSMutableArray *namesArray;
}
@property (nonatomic, retain) NSMutableArray *namesArray;
@end
@implementation RootViewController
@synthesize namesArray;
- (void)viewDidLoad{
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:@"names" ofType:@"plist"];
NSMutableArray *tempArray = [[NSMutableArray alloc]initWithContentsOfFile:path];
self.namesArray = tempArray;
[tempArray release];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [namesArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [namesArray objectAtIndex:indexPath.row];
return cell;
}
任何人都可以告诉我根据上述场景的 MVC 模式构建我的模型的正确方法吗?我猜我会使用单例来返回一组 Name 对象。我基本上想学习使用 Model 对象来表示我的数据的正确方式。
最佳答案
iOS MVC 中的模型简单地划分了您的应用程序,以便将数据和应用程序算法(模型)与表示和事件处理代码分开。因此,请考虑创建一个新的模型类来获取、设置和保存您的应用程序数据。此类应该不了解 GUI。
这是一个通过处理加密解密来包装应用程序算法的模型示例。
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonCryptor.h>
#import <CommonCrypto/CommonDigest.h>
#import <Security/Security.h>
@interface Model : NSObject {
}
+(id)modelGetInstance;
+(NSData *)getRandomIV:(NSInteger)numBytes;
-(id)init;
-(NSString*)encrypt:(NSString*)plainText password:(NSString*)pw; // public
-(NSString*)decrypt:(NSString*)cipherText password:(NSString*)pw; // public
@end
这类似于 UNIX ENGINE-INTERFACE。这不是 Smalltalk 的 MVC,其中 View 直接通过 MODEL(观察者模式)的更改进行更新。
关于iphone - 如何使用模型对象代替数组和字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6241036/