2013-07-15 68 views
0

我有以下型號的模型創建字典:爲 我想getSomeInfo返回的NSDictionary(例如{ 「名字」,self.firstName}):從包含零值

@interface Person : NSObject 

@property (nonatomic, copy) NSString *firstName; 
@property (nonatomic, copy) NSString *middleName; 
@property (nonatomic, copy) NSString *lastName; 
@property (nonatomic, copy) NSString *status; 
@property (nonatomic, copy) NSString *favoriteMeal; 
@property (nonatomic, copy) NSString *favoriteDrink; 
@property (nonatomic, copy) NSString *favoriteShow; 
@property (nonatomic, copy) NSString *favoriteMovie; 
@property (nonatomic, copy) NSString *favoriteSport; 

-(NSDictionary *)getSomeInfo; 
-(NSDictionary *)getAllInfo; 

@end 

第1部分所有不包含零的字段。我怎樣才能做到這一點? (我可以檢查每一個值,但我不知道是否有更好的方法)

第2部分: 我想getAllInfo與所有的財產返回的NSDictionary,如果一個包含零,那麼它應該拋出一個錯誤。我還需要寫一個長條件語句來檢查還是有更好的方法?

注意:我想這樣做,而不使用外部庫。我是新來的語言,所以如果Objective-C中有更好的模式,我會接受建議。

+0

看看http://stackoverflow.com/a/2302808/550672讓你開始吧 – Zeophlite

+0

或'dictionaryWithVakuesForKeys:'。 – Wain

+0

與Objective-C中的不可恢復錯誤通常被保留(意味着退出應該很快發生),與Java和Python等語言不同。考慮使用NSError作爲out參數,或者甚至只是將字典中的值設置爲'[NSNull null]'。 – Kitsune

回答

1

有兩種方法。

1)檢查各值:

- (NSDictionary *)getSomeInfo { 
    NSMutableDictionary *res = [NSMutableDictionary dictionary]; 

    if (self.firstName.length) { 
     res[@"firstName"] = self.firstName; 
    } 
    if (self.middleName.length) { 
     res[@"middleName"] = self.middleName; 
    } 
    // Repeat for all of the properties 

    return res; 
} 

2)使用KVC(鍵 - 值編碼):

- (NSDictionary *)getSomeInfo { 
    NSMutableDictionary *res = [NSMutableDictionary dictionary]; 

    NSArray *properties = @[ @"firstName", @"middleName", @"lastName", ... ]; // list all of the properties 
    for (NSString *property in properties) { 
     NSString *value = [self valueForKey:property]; 
     if (value.length) { 
      res[property] = value; 
     } 
    } 

    return res; 
} 

getAllInfo方法,你可以這樣做,但如果有的話,而不是返回nil值缺失。將nil結果視爲您的跡象表明並非所有屬性都有價值。

+0

哦,夥計!當我開始閱讀關於KVC時,我就是這樣,正是我所期待的。它真的削減了很多樣板代碼。謝謝! – Jimmy