2014-09-30 23 views
-1

首先看看下面的Objective-C代碼:中的NSMutableDictionary處理異常

NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init]; 
NSMutableDictionary *oldDict = [[NSMutableDictionary alloc] initWithContentsOfFile: oldDictPath]; 
@try { 
     [newDict setObject:[oldDict objectForKey:@"count"] forKey:@"newCount"]; 
} 
//I want to take "count" value from oldDict and set this to NewDict 
@catch (NSException *exception) { 
     NSLog(@"%@ ",exception.name); 
     NSLog(@"Reason: %@ ",exception.reason); 
} 
@finally { 
     NSLog(@"@@finaly Always Executes"); 
} 

我想借此從oldDict「計數」的值,並設置這NewDict.And問題是[oldDict objectForKey:@"count"]可能 sometime.This可以通過if條件等

if([oldDict objectForKey:@"count"] != nil){ //then add to newDict} 

OldDict被處理可以具有1000對,所以我不想把1000 if statements

上述代碼中的@try和@catch未處理此異常。任何機構能告訴我處理這種例外的最佳方法嗎? 我的代碼崩潰了。

回答

0

嘗試這樣的,沒有必要添加一個嘗試捕捉只需要調用zeroIfNil或進行必要的功能就像emptyIfNull

-(void)someFunc 
{ 
    NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init]; 
    NSMutableDictionary *oldDict = [[NSMutableDictionary alloc] initWithContentsOfFile: oldDictPath]; 

    [newDict setObject:[self zeroIfNil:[oldDict objectForKey:@"count"]] forKey:@"newCount"]; 
    // TODO : Access all values of of oldDict here and parse them with the 
    // help of custom functions as i suggested. 
} 

-(NSString *)zeroIfNil:(id)object 
{ 
    if(object == nil) { 
     return @"0"; 
    } 
    else { 
     return object; 
    } 
} 
0
NSDictionary *keys = @{ @"count": @"newCount", @"asdf": @"newAsdf" }; 

for (id key in keys) { 
    id object = [oldDict objectForKey:key]; 
    if (object) [newDict setObject:object forKey:[keys objectForKey:key]]; 
} 

編輯:這個片段定義keys字典映射舊密鑰新的密鑰並對其進行迭代,分配oldDict [oldKey]到newDict [則newkey對於存在於oldDict鍵。這避免了數千個賦值的手動編碼,以及在問題中觀察到的異常處理。