2016-07-20 61 views
0

我有一類對象轉換中的NSDictionary如何將一個類對象轉換爲一個NSDictionary?

我有以下類

@interface FoodMeal : NSObject<NSCoding,NSCopying> 

@property (nonatomic,strong) NSString *mealType; 
@property (nonatomic,strong) NSString *mealName; 
@property (nonatomic,strong) NSArray *mealItems; 
@property (nonatomic,strong) NSDate *mealDate; 

@end 

mealItems包含FoodItems這是一個類的對象。

FoodItems有一個變量營養事實實習生類對象。

是否有一種將FoodMeal類轉換爲NSDictionary的有效方法。

在此先感謝。

+0

看到這個非常簡單的HTTP://計算器.com/questions/19079862 /轉換-nsobject-to-nsdictionary –

+0

我已經看到了解決方案...我必須添加手冊的所有內容到詞典?有沒有其他有效的解決方案.. –

+0

你可以嘗試[獲取所有的屬性名稱](http://stackoverflow.com/questions/780897/how-do-i-find-all-the-property-keys-of- a-kvc-compliant-objective-c-object),然後使用'valueForKey:'來獲得它們的值。 – Droppy

回答

2

可以使用jsonmodel

PLZ看到此鏈接https://github.com/jsonmodel/jsonmodel

例如:

下載jsonmodel進口在您的Xcode,項目

然後

@interface FoodMeal : JSONModel 

@property (nonatomic,strong) NSString *mealType; 
@property (nonatomic,strong) NSString *mealName; 
@property (nonatomic,strong) NSArray *mealItems; 
@property (nonatomic,strong) NSDate *mealDate; 

@end 

使類jsonmodel的子類。 jsonmodel超類是NSObject。

當你想你的類對象轉換爲字典,然後使用它像這樣

FoodMeal *ob = [FoodMeal alloc]init]; 

NSDictionary *dictob = [ob toDictionary]; 

toDictionary比在JSONModel方法返回你的NSDictionary;

+0

@Droppy你使用jsonmodel嗎? –

+0

看到我給出的鏈接@Droppy。 –

+0

我想說第一次使用它比把@Droppy的問題。 –

1

它只是寫在你的FoodMeal

- (NSDictionary *)dictionaryRepresentation 
{ 
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary]; 

    [mutableDict setValue:self.mealType forKey:@"KeyForMealType"]; 
    [mutableDict setValue:self.mealName forKey:@"KeyForMealName"]; 
    [mutableDict setValue:self.mealItems forKey:@"KeyForMealItem"]; 
    [mutableDict setValue:self.mealDate forKey:@"KeyForMealDate"]; 

    return [NSDictionary dictionaryWithDictionary:mutableDict]; 
} 

的方法之後,一旦你的想法,你可以用這個方法

FoodMeal *food = [FoodMeal alloc] init]; 
food.mealType = @"ABC"; 
food.mealName = @"DEF" 
food.mealItems = @[@"Item 1", @"Item 2",@"Item 3",@"Item 4"]; 
food.mealDate = [NSDate date]; 

[food dictionaryRepresentation]; 
+1

hmmm意味着我必須不斷爲每個對象創建可變字典...我必須深入探究mealItems數組..因爲Item1再次一類說營養,10-12屬性服務... –

+0

其處理NSArray的NSDictionary責任。 順便說一句,你想用對象的字典做什麼,可能一些其他的解決方案可以幫助你 –

相關問題