场景:减少循环语句的多次遍历,提高程序的运行效率。
例子:
example.h
#import <Cocoa/Cocoa.h>
@interface UiApp : NSObject
@property (readwrite,copy) NSString *app_id;
@property (readwrite,copy) NSString *app_name;
@property (readwrite,assign) NSMutableArray *allFiles;
@property (readwrite,assign) NSMutableDictionary *findDictionary;
@end
@interface UiFile : NSObject
@property (readwrite,copy) NSString *name;
@property (readwrite,copy) NSString *path;
@end
@interface Example : NSObject
+(void) findFile;
@end
example.m
#import "Example.h"
@implementation UiApp
@synthesize app_id,app_name,allFiles,findDictionary;
-(id) init
{
self =[super init];
allFiles =[NSMutableArray new];
findDictionary =[NSMutableDictionary new];
return self;
}
-(void) dealloc
{
[app_id release];
[app_name release];
[super dealloc];
}
@end
@implementation UiFile
@synthesize path,name;
-(void) dealloc
{
[name release];
[path release];
[super dealloc];
}
@end
@implementation Example
+(void) findFile
{
//存入数据的时候,把数据进行封装
NSMutableArray *array =[NSMutableArray new];
NSMutableDictionary *dictionary =[NSMutableDictionary new];
for (int i =1; i<=5; i++) {
UiApp *app =[UiApp new];
[app setApp_id:[NSString stringWithFormat:@"%d",i]];
[app setApp_name:[NSString stringWithFormat:@"app%d",i]];
for (int j=0; j<5; j++) {
UiFile *file =[UiFile new];
[file setName:[NSString stringWithFormat:@"file%d%d",i,j]];
[file setPath:[NSString stringWithFormat:@"path:%d%d",i,j]];
[app.allFiles addObject:file];
[app.findDictionary setObject:file forKey:file.path];
}
[array addObject:app];
[dictionary setObject:app forKey:app.app_id];
}
//把UiFile对象查找出来。
NSString *app_id =@"2";
NSString *filePath =@"path:21";
//方法1.一般的方法,对数组进行多次遍历查找,直到找到为止。这是效率非常低的做法,不可采取
for(UiApp *app in array)
{
if ([app_id isEqualToString:app.app_id])
{
for (UiFile *file in app.allFiles)
{
if ([filePath isEqualToString:file.path])
{
NSLog(@"1.成功找到:%@,%@",file.name,file.path);
break;
}
}
break;
}
}
//方法2.使用词典高效查找file;
//查找词典,通过关键字找出对应的object
UiApp *findApp =[dictionary objectForKey:app_id];
UiFile *findFile =[findApp.findDictionary objectForKey:filePath];
[findApp.allFiles removeObject:findFile];
NSLog(@"2.成功找到:%@,%@",findFile.name,findFile.path);
[array release];
[dictionary release];
}
@end
main.m
#import <Foundation/Foundation.h>
#import "Example.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
[Example findFile];
}
return 0;
}
运行结果:
结论:
方法一和方法二进行比较,很明显方法二的查找效率比方法一高很多;方法一在循环里再遍历查找数据效率非常低。所以用到要查找数据的时候,我们不妨用
NSMutableDictionary高效查找。