ios - 通过创建 NSDictionary 优化功能

标签 ios objective-c xcode optimization nsmutabledictionary

我正在尝试像这样优化返回 NSMutableDictionary 的函数:

 -(NSMutableDictionary *)getValuses{

    NSNumber *n1 = [NSNumber numberWithInt:-1];
    NSNumber *n2 = [NSNumber numberWithInt:-1];
    NSNumber *n3 = [NSNumber numberWithInt:-1];
    NSNumber *n4 = [NSNumber numberWithInt:-1];
    NSNumber *n5 = [NSNumber numberWithInt:-1];

    if (self.k1)
        n1 = self.k1;
    if (self.k2)
        n2 = self.k2;
    if (self.k3)
        n3 = self.k3;
    if (self.k4)
        n4 = self.k4;
    if (self.k5)
        n5 = self.k5;

    NSMutableDictionary * dictionary = [[NSMutableDictionary alloc]initWithObjectsAndKeys:n1,[NSNumber numberWithInt:2],n2,[NSNumber numberWithInt:3],n3,[NSNumber numberWithInt:4],n4,[NSNumber numberWithInt:5],n5,[NSNumber numberWithInt:6], nil];

    return dictionary;
}  

我在循环中运行这个函数超过 100 万次,所以任何优化都是好的。它可以工作,但我希望它工作得更快。

最佳答案

你真的需要 -1 值的字典吗? 你可以避免所有“if/then”的东西(我听说它对于 cpu 来说可能很慢)如果你只是这样做

    NSMutableDictionary * dictionary = [[NSMutableDictionary alloc]initWithObjectsAndKeys:k1,[NSNumber numberWithInt:2],k2,[NSNumber numberWithInt:3],k3,[NSNumber numberWithInt:4],k4,[NSNumber numberWithInt:5],k5,[NSNumber numberWithInt:6], nil];
    // then you can do things like this
    id obj = [dictionary objectForKey:@2];
    if (obj)
        NSLog(@"dict with good values");
    else
        NSLog(@"old dict with -1");

关于ios - 通过创建 NSDictionary 优化功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19583411/

相关文章:

iPhone : How to call other method from [_assetExport exportAsynchronouslyWithCompletionHandler: ^(void ) { }

objective-c - Xcode:如何使用滑动手势更改 UIPageControl 值?

ios - 使用 JAVAPNS 成功发送推送但未在客户端设备中接收

objective-c - 什么是 Objective-C 运行时中的类处理程序回调?

objective-c - 子类化 CCSprite 的优势

iphone - 如何在 iOS 中重用代码(IBAction)?

objective-c - 使用 segue 在 Storyboard中的 View Controller 之间传递数据

iphone - 如何垂直移动带有 slider 的 UILabel

iphone - 一个接一个地运行动画失败

ios - PFQueryTableViewController 使用 includeKey 加载一行