2014-07-20 1 views
0

"일"에 정확한 emoAvg를 유지하고 싶습니다.to-many 관련 NSManagedObject 하위 클래스가 변경되면 NSManagedObject 하위 클래스를 업데이트하는 방법은 무엇입니까?

  1. 갱신에 "감정"이 "날"에 관련 될 때마다 "날"의 emoAvg은 ... 하루에 많은 감정을 가질 수 있습니다 여기에 내가 달성 찾고 있어요거야.
  2. 갱신에 "감정"이 "날"에서 제거 될 때마다 "날"의 emoAvg
  3. 업데이트 "날"의 emoAvg 때마다 "감정"변화의 감정 속성입니다.

enter image description here

I 모델 층에있는 모든이 코드를 유지하려면 내가 감정을 만들 때 감정에 날을 첨부 다음 코드를 호출하여 일에 감정을 연결할 수 있었다.

"일"에 "감정"이있는 일대 다 관계에 대한 사용자 지정 접근자는 쓸 수 없었습니다. Xcode 4.6.2에서 멈추었 고 Copy/paste 커스텀 ObjectiveC 접근 자 기능이이 버전에 존재하지 않는 것 같습니다.

이 코드를 작성하는 좋은 방법은 무엇입니까?

- (void)setDate:(NSDate *)date 
{ 
    [self willChangeValueForKey:@"date"]; 
    [self setPrimitiveValue:date forKey:@"date"]; 

    [self associateDay]; 

    [self didChangeValueForKey:@"date"]; 

} 

-(void)associateDay 
{ 
    NSCalendar *calendar = [NSCalendar currentCalendar]; 

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setTimeStyle:NSDateFormatterMediumStyle]; 
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; 

    NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:self.date]; 

    //Start of Day 
    [dateComponents setHour:0]; 
    [dateComponents setMinute:0]; 
    [dateComponents setSecond:0]; 
    NSDate *startOfDay = [calendar dateFromComponents:dateComponents]; 
    //NSLog(@"Start of Day:  %@", [dateFormatter stringFromDate:startOfDay]); 

    //End of Day 
    [dateComponents setHour:23]; 
    [dateComponents setMinute:59]; 
    [dateComponents setSecond:59]; 
    NSDate *endOfDay = [calendar dateFromComponents:dateComponents]; 
    //NSLog(@"End of Day:   %@", [dateFormatter stringFromDate:endOfDay]); 

    //Find all Day Entities that fall on the same calendar date 
    NSPredicate *datePredicate = [NSPredicate predicateWithFormat:@"date > %@ AND date < %@", startOfDay, endOfDay]; 
    NSFetchRequest *fetchDays = [[NSFetchRequest alloc]initWithEntityName:@"Day"]; 
    fetchDays.predicate = datePredicate; 
    NSManagedObjectContext *context = [(id)[UIApplication sharedApplication].delegate managedObjectContext]; 
    NSArray *daysFound = [context executeFetchRequest:fetchDays error:nil]; 

    if ([daysFound count] == 1) 
    { 
     Day *dayWithMatchingDate = [daysFound objectAtIndex:0]; 
     self.day = dayWithMatchingDate; 
     NSLog(@"Found %d matching days",[daysFound count]); 
    } 

    if ([daysFound count] > 1) 
    { 
     NSLog(@"Found %d matching days...Something needs fixing",[daysFound count]); 
    } 

    if ([daysFound count] < 1) 
    { 
     NSLog(@"Found %d matching days...Making a new Day and associating it",[daysFound count]); 
     NSManagedObjectContext *context = [(id)[UIApplication sharedApplication].delegate managedObjectContext]; 
     Day *newDay = [NSEntityDescription insertNewObjectForEntityForName:@"Day" inManagedObjectContext:context]; 
     newDay.date = self.date; 
     self.day = newDay; 
    } 
} 

답변

0

나는 반드시 데이터 모델의 일부로서 Day을 모델링하는 것은 좋은 생각이 아니다라고 생각합니다. 기존 날짜 속성은 선택, 필터링 및 기타 논리에 충분해야합니다.

그럼에도 불구하고 올바른 방향으로 가고 있습니다. 열쇠는 세터를 오버라이드하는 것입니다. EmotionDay (내 팁 : 카테고리 감정 Emotion+Additions에서이 코드를 기본 모델 클래스와 구분하여 작성)에서 다음 설정을 재정의해야합니다. Day

예에서 Day

  • addEmotionsObjectEmotion
  • removeEmotionsObject

    1. setEmotion

      -(void)removeEmotionsObject:(Emotion)value { 
          NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1]; 
          [self willChangeValueForKey:@"emotions" 
           withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects]; 
          [[self primitiveEmotions] removeObject:value]; 
          [self didChangeValueForKey:@"emotions" 
           withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects]; 
      } 
      

      코어 데이터 프로그래밍 가이드의 relevant section에서 이러한 접근 자에 대한 자세한 내용입니다.

  • +0

    먼디, 응답 해 주셔서 감사합니다. 질문을하기 전에 내가 링크 한 섹션을 읽었습니다. 당신은 "[[self primitiveEmotions] removeObject : value];" 그 코드의 출처가 확실하지 않습니다. – Aaronium112

    +0

    모든 관리 객체'attribute'는'setPrimitiveAttribute'와 같은 메소드에 의해 자동으로 지원됩니다. 'removeObject'는 일반적인 NSSet 인스턴스 메소드입니다. – Mundi

    0

    나는 작업을 요청한 코드를 얻을 수있었습니다. 그러나 엉망입니다. NSNotificationCenter를 사용하여 관련 객체의 변경 사항을 관찰하는 것이 더 좋습니다. 다음은 작동하는 코드입니다. 나를 돕기 위해 Mundi에게 소품을 제공해야합니다.

    - (void)addEmotionsObject:(Emotion *)value 
    { 
        NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1]; 
    
        [self willChangeValueForKey:@"emotions" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects]; 
    
        [[self primitiveEmotions] addObject:value]; 
    
        [self calculateEmotionalAverage]; 
    
        [self didChangeValueForKey:@"emotions" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects]; 
    } 
    
    - (void)removeEmotionsObject:(Emotion *)value 
    { 
        NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1]; 
    
        [self willChangeValueForKey:@"emotions" withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects]; 
    
        [[self primitiveEmotions] removeObject:value]; 
    
        [self calculateEmotionalAverage]; 
    
        [self didChangeValueForKey:@"emotions" withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects]; 
    } 
    
    
    
    - (void)addEmotions:(NSSet *)value 
    { 
        [self willChangeValueForKey:@"emotions" withSetMutation:NSKeyValueUnionSetMutation usingObjects:value]; 
    
        [[self primitiveEmotions] unionSet:value]; 
    
        [self calculateEmotionalAverage]; 
    
        [self didChangeValueForKey:@"emotions" withSetMutation:NSKeyValueUnionSetMutation usingObjects:value]; 
    } 
    
    
    
    - (void)removeEmotions:(NSSet *)value 
    { 
        [self willChangeValueForKey:@"emotions" withSetMutation:NSKeyValueMinusSetMutation usingObjects:value]; 
    
        [[self primitiveEmotions] minusSet:value]; 
    
        [self calculateEmotionalAverage]; 
    
        [self didChangeValueForKey:@"emotions" withSetMutation:NSKeyValueMinusSetMutation usingObjects:value]; 
    } 
    
    
    -(void)calculateEmotionalAverage 
    { 
        float emotionalTotal = 0; 
        for (Emotion *emo in self.emotions) 
        { 
         if ([emo.emotion isEqualToString:@"Joy = 22"]){ 
          emotionalTotal += 22.0; 
         } 
         NSLog(@"%f",emotionalTotal); 
        } 
    } 
    
    관련 문제