如何针对NSArrays优化此代码?

时间:2012-02-02 00:35:26

标签: iphone objective-c cocoa-touch

我觉得我在这里做了很多不必要的事情:

- (id)init {
    if ((self = [super init])) {            
        NSMutableArray *anArray = [[NSMutableArray alloc] init];
        self.currentScopeArray = anArray;
        [anArray release];

        NSString *aPath = [[NSBundle mainBundle] pathForResource:@"Configuration" ofType:@"plist"];
        NSMutableDictionary *aDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:aPath];
        NSMutableArray *anotherArray = [[NSMutableArray arrayWithObject:[aDictionary objectForKey:@"Search"]] objectAtIndex:0];
        self.defaultScopeArray = anotherArray;
        [aDictionary release];

        for (int x = 0; x < [self.defaultScopeArray count]; x++) {
            BOOL enableCheckmark = [[[self.defaultScopeArray objectAtIndex:x] objectForKey:@"enabledByDefault"] boolValue];
            if (enableCheckmark) {
                if (![self.currentScopeArray containsObject:[self.defaultScopeArray objectAtIndex:x]]) {
                    [self.currentScopeArray addObject:[self.defaultScopeArray objectAtIndex:x]];
                }
            }
        }
    }
    return self;
}

1 个答案:

答案 0 :(得分:2)

至少,您可以替换此块:

NSMutableArray *anArray = [[NSMutableArray alloc] init];
self.currentScopeArray = anArray;
[anArray release];

使用:

self.currentScopeArray = [NSMutableArray array];

这个区块:

NSString *aPath = [[NSBundle mainBundle] pathForResource:@"Configuration" ofType:@"plist"];
NSMutableDictionary *aDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:aPath];
NSMutableArray *anotherArray = [[NSMutableArray arrayWithObject:[aDictionary objectForKey:@"Search"]] objectAtIndex:0];
self.defaultScopeArray = anotherArray;
[aDictionary release];

可能是:

NSString *aPath = [[NSBundle mainBundle] pathForResource:@"Configuration" ofType:@"plist"];
NSMutableDictionary *aDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:aPath];
self.defaultScopeArray = [NSMutableArray arrayWithObject:[aDictionary objectForKey:@"Search"]] objectAtIndex:0];