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

       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就是排序好的数组了。

posted on 2012-01-07 21:51  风泽海  阅读(450)  评论(0编辑  收藏  举报

导航