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

代码是转贴过来的,稍微做了修改

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值