2010-12-02 37 views
1

我有2個核心數據實體:Question和QuestionType。每個問題都有1個QuestionType。使用核心數據實體作爲枚舉?

QuestionType具有typeName字符串屬性;這主要是我如何確定它是哪個QuestionType。它被固定到幾個不同類型的列表。我想知道是否可以使用數據中所有QuestionType的列表作爲枚舉,或者如果不可以,使用此列表將QuestionType指定給問題的最佳方法是什麼,並在稍後檢查QuestionType?

目前,當我想以一個類型分配給一個問題(基於瞭解的typeName),我這樣做:

NSFetchRequest *questionTypeFetchRequest = [[NSFetchRequest alloc] init]; 
questionTypeFetchRequest.entity = [NSEntityDescription entityForName:@"QuestionType" inManagedObjectContext:self.managedObjectContext]; 
NSPredicate *questionTypePredicate = [NSPredicate predicateWithFormat:@"typeName like %@", [questionData objectForKey:@"questionType"]]; 
questionTypeFetchRequest.predicate = questionTypePredicate; 
question.questionType = [[self.managedObjectContext executeFetchRequest:questionTypeFetchRequest error:&error] objectAtIndex:0]; 

這似乎是很多工作只是一個QuestionType分配給我題!我必須爲其他類似的實體重複這一點。

,然後當我想以後檢查QuestionType,我做:

if ([question.questionType.typeName isEqualToString:@"text"]){ 

這工作得很好,但我覺得我應該在question.questionType進行比較,我要找的具體QuestionType ,而不僅僅是比較typeName。

有什麼辦法來建立一個枚舉持本人QuestionTypes,這樣我可以做到這一點:

question.questionType = Text; 
switch(question.questionType) 
{ 
    case Text: 

回答

1

是否questionType必須是一個對象?如果你想使用枚舉,你可以聲明實體的屬性是一個整數,而不是另一個實體,如QuestionType

或者,你可以聲明你的questionType屬性是一個字符串,並直接在那裏保存typeName

即使使用枚舉,語法也不像C/Objective-C中的EnumName.EnumKind。查看任何教科書的語法。

如果繼續使用questionType作爲一個整體,我建議你到緩存在字典中獲取結果,如:

(QuestionType*)questionTypeWithName:(NSString*)name 
    { 
     static NSMutableDictionary*dict=nil; 
     if(!dict){ 
      dict=[[NSMutableDictionary alloc] init]]; 
     } 
     QuestionType*qt=[dict objectForKey:name]; 
     if(qt){ 
       return qt; 
     }else{ 
      NSFetchRequest *questionTypeFetchRequest = [[NSFetchRequest alloc] init]; 
       ... 
      NSArray*result = ... executeFetchRequest: ... 
      if(result){ 
        ... 
        add the resulting qt to the dict ... 
        ... 
      }else{ 
        create a new QuestionType entity with a given name 
        add it to the dict. 
        return it. 
      } 
     } 
    } 

和類似的東西。

+0

謝謝!已更新以修復Enum語法。它需要成爲managedObject,因爲可能的questionTypes列表應該能夠通過重新編譯以外的其他方式進行更新,並且因爲它可能包含typeName以外的其他屬性。但我相信靜態字典會給我我想要的。 – GendoIkari 2010-12-03 14:34:56