iOS開發設計策略模式

來源:互聯網
上載者:User

標籤:ios開發   設計   程式員   加密   架構   

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


iOS開發設計策略模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.