2011-06-29 34 views
1

我有一點使用JSONKit的反序列化。它正在工作,但我寫的感覺很笨拙。任何人都可以提出一些改進建議:)iPhone - JSONKit - 工作,但我使用它嗎?

//call web service with url and staff id 
    NSString *result = [MobileAppDelegate webServiceExecuteGetSingleWithId:StaffId 
    atUrl:@"XXXXXXXX"]; 

    //create NSDictionary from JSON return type 
    NSDictionary *items = [result objectFromJSONString]; 

    NSArray *ar = (NSArray*)[items objectForKey:@"SummaryJsonResult"]; 

    for(int i = 0; i < [ar count]; i++){ 
     NSDictionary *tmpDict = (NSDictionary*)[ar objectAtIndex:i]; 
     AlertItem *tmpItem = [[AlertItem alloc] init]; 
     tmpItem.Description = [tmpDict objectForKey:@"Description"]; 
     tmpItem.NumItems = [tmpDict objectForKey:@"ItemCount"]; 
     tmpItem.ModuleGroup = [tmpDict objectForKey:@"ModuleGroup"]; 
     tmpItem.StaffID = [tmpDict objectForKey:@"StaffID"]; 
     tmpItem.status - [tmpDict objectForKey:@"Status"]; 
     [array addObject: tmpItem]; 
     [tmpItem release]; 
    } 

回答

2

這基本上是你如何去做的。你可以乾淨的東西一點點:

使用for-in循環:

for (NSDictionary *tmpDict in [items objectForKey:@"SummaryJsonResult"]) { 
    ... 

重構創建從字典的AlertItem到工廠方法:

+ (AlertItem *)alertItemWithDictionary:(NSDictionary *)dict { 
    AlertItem *item = [[self alloc] init]; 
    ...do the same stuff you do in the loop 
    return [item autorelease]; 
} 

... then in the loop you just do: 
[array addObject:[AlertItem alertItemWithDictionary:tempDict]]; 
+0

好的,謝謝你的建議。我想知道是否有方法從NSDictionary,NSArray然後回到NSDictionary。它似乎應該有某種對象可以爲所有三個做? – shaw2thefloor

1

首先,它似乎就好像你在同步執行你的請求一樣,這通常是一個壞主意。如果您在主線程中執行此操作,則會阻止所有用戶交互,直到請求完成。

您的代碼也不處理任何格式錯誤的數據。如果您的JSON中的任何對象的類型與您預期的不同,那麼您的應用程序將會崩潰。如果「SummaryJsonResult」指向一個字典而不是一個數組,那麼在嘗試發送objectForKey:消息時會出現「無法識別的選擇器」異常。您可以使用isKindOfClass:respondsToSelector:來防止這種情況。

+0

好的,謝謝你。我會將其更改爲異步請求。如果你不知道它的確切格式,有沒有什麼特別好的方法可以從json中獲取數據。我打電話給自己的網絡服務,所以我可以控制返回的內容,但如果還有其他方法,它會很好。 – shaw2thefloor

+0

事情是與異步請求,是我使用數組來填充UITableView,所以如果我做一個asyc請求,它不會開始嘗試填充數據數組已填充表視圖...我認爲這會導致一個空指針? – shaw2thefloor

+0

您可以將其初始化爲空數組。你甚至不必這樣做,因爲實例變量會自動初始化爲零,並且向nil發送消息(在這種情況下爲'count')會根據上下文返回0或零。 – omz

相關問題