iOS策略模式的简单应用

在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中的时间对象的时间排序。具体操作如下:

XXX.h文件

1
2
3
4
5
6
@interface NSMutableDictionary(myCompare)
-(NSComparisonResult)myCompareMethodWithDict: (NSMutableDictionary*)theOtherDict;
@end

XXX.m文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@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对象的数组。

1
2
3
4
5
    NSString* documentsDirectory = [paths objectAtIndex:0];
NSString *plistPath = [NSString stringWithFormat:@"%@/XXX.plist",documentsDirectory];
     NSMutableDictionary * cacheData = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
[cacheArray sortUsingSelector:@selector(myCompareMethodWithDict:)];//根据年龄降序排序
这样,cacheArray就是排序好的数组了。

最近做的一个通讯录应用中有个需求需要对用户展示的位置进行排序。返回的数据json解析后存在了sqlite的[数据库](http://lib.csdn.net/base/14)中了。

那么解决的方法有两种

1,sql排序 :没有什么新的东西,主要学习了在sqlite中用sql语句实现left join,union的相关操作,在Xcode中sql语句太长了显得不太好看,那么推荐navi猫中把业务处理好后再粘贴到Xcode中进行修改

2,策略模式:对mutalbeArray的元素(这里并不是你一个Dictionnary,而是一个自定义的Model)我们同样可以给这个mutalbeArray中的元素一个策略。