您的位置:首页 > 移动开发 > IOS开发

iOS开发设计策略模式

2014-11-25 09:50 435 查看
iOS应用能加密?全球都没有的技术,你造吗?作为开发iOS应用的,是不是感到自己out啦?快来看看什么是iOS应用加密:http://www.ijiami.cn/newsInfo?id=541&v=2

在iOS开发中,使用官方框架,官方sdk中,可以接触到不少设计模式,可能平时没有注意,实际上已经用到了不少设计模式

下面举一个例子:

策略模式:至于什么是策略模式,请自己百度吧,我也说不清楚,但是知道怎么用,下面结合代码详细说明

比方我有一个NSMutableArray,里面每个元素都是一个NSDictionary,其中NSDictionary有不少“键--值”对,我想以“键1对应的值1”为标准,对NSMutableArray进行排序。

NSMutableArray

---NSDictionary1

------“name”:"zhangsan"

------“age”:“30”

---NSDictionary2

------“name”:"lisi"

------“age”:“28“

---NSDictionary3

------“name”:"lisi"

------“age”:“48“

下面我需要针对”age“字段进行排序

那么策略模式在这里就是这么展示的:你丢给NSMutableArray对象一个排序的方法(一个策略),那么他就拿这个方法对内部的元素进行排序,你丢给他不同的方法(也就是不同的策略<实际的每个策略,不简单是一个参数,而是做一件事情的完整过程>),他就给你不同的结果。

下面贴代码

NSArray中存放的是NSDictionary,可以使用策略的方法对NSDictionary进行定制,增加比较的方法。然后调用NSArray的sortUsingSelector方法对数组进行排序,这里使用NSDictionay中的时间对象的时间排序。具体操作如下:

1.定制NSDictionary

XXX.h文件

@interface NSMutableDictionary(myCompare)

-(NSComparisonResult)myCompareMethodWithDict: (NSMutableDictionary*)theOtherDict;

@end

XXX.m文件

#import "CustomDictionary.h"





@implementation NSMutableDictionary(myCompare)

- (NSComparisonResult)myCompareMethodWithDict:(NSMutableDictionary*)anotherDict

{

NSMutableDictionary *firstDict = self;

int iSelfAge =[ [firstDict objectForKey: @"age"]intValue];

int iOtherAge = [[anotherDict objectForKey: @"age"]intValue];



//return [firstDate compare: secondDate];

// //NSOrderedAscending = -1, NSOrderedSame, NSOrderedDescending}

if(iSelgAge<iOtherAge)return NSOrderedAscending;

else if (iSelgAge==iOtherAge)return NSOrderedSame;

else return NSOrderedDescending;



}

@end



2.使用myCompareMethodWithDict对NSArray进行排序,假设NSArray是从plist文件中读取的NSDictionary对象的数组。

NSString* documentsDirectory = [paths objectAtIndex:0];

NSString *plistPath = [NSString stringWithFormat:@"%@/XXX.plist",documentsDirectory];

NSMutableDictionary * cacheData = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];

[cacheArray sortUsingSelector:@selector(myCompareMethodWithDict:)];//根据年龄降序排序

这样,cacheArray就是排序好的数组了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: