Chinaunix首页 | 论坛 | 博客
  • 博客访问: 134801
  • 博文数量: 34
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 700
  • 用 户 组: 普通用户
  • 注册时间: 2014-11-12 16:52
文章分类

全部博文(34)

文章存档

2015年(13)

2014年(21)

我的朋友

分类: iOS平台

2014-11-25 11:15:29

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进行定制,增加比较的方法。然后调用NSArraysortUsingSelector方法对数组进行排序,这里使用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

 

     else if (iSelgAge==iOtherAge)return NSOrderedSame; 

 

    else return NSOrderedDescending;

 

 

 

}

 

@end

 

 

 

        2.使用myCompareMethodWithDictNSArray进行排序,假设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就是排序好的数组了。


更多精彩内容请点击

 

 

阅读(1195) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~