iphone - 如何使用模型对象代替数组和字典?

标签 iphone objective-c ios model-view-controller

下面是一个简单示例,说明我如何从 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/

相关文章:

iphone - OpenGL : Finding out your current position

iphone - 自定义函数 "indexpath"

ios - SpriteKit,使用加速度计返回前景时, Sprite 移动得非常快

iOS MDM 配置文件和设置 key

ios - 以编程方式创建 UINavigationBar

iphone - 如何注册应用程序以响应自定义 URL 方案打开请求?

iphone - 如何以编程方式暂停 NSTimer?

ios - UIImagePickerController教程?

ios - 在 SwiftUI NavigationView 中呈现 UINavigationBar 的旧小标题

iphone - iOS - UITableView 非静态背景图片