1

seen others은 managedObjectContext 외부에서 NSManagedObject를 사용하는 방법을 묻습니다. 모두가 그렇다고 말하면서는 안된다고 말하지만 대신해야 할 일에 대한 정보를 찾을 수 없습니다.managedObjectContext 외부의 NSManagedObject

필자는 본질적으로 내 NSManagedObject에 설정된 데이터로 두 가지 다른 작업을 수행하려고합니다. 을 persistentStore에 저장하고 원격 서버로 보내려고합니다. 내 아이디어 alloc/init 내 NSManagedObject의 인스턴스, 해당 속성을 채 웁니다 다음 그 속성을 해당 속성을 제대로 전달 된 수 NSManagedObject, 전달할 수 및 다음 다른 함수에 전달하는 것입니다 책임을 질 것입니다 서버에 데이터를 보내기위한 것. 코드에서

: 당신이 기대하는 바와 같이,이 내가 propertyA을 설정하려고 두 번째 줄에 실패

 
// in my view controller 
Event *event = [Event alloc] init]; 
event.propertyA = @"foo"; 
event.propertyB = @"bar"; 

[self logEvent:event]; 
[self sendEvent:event]; 

----------------------------------- 

// method in view controller 
- (void)logEvent(Event *)event { 
    // my thought was to take the event that I manually created, and use it to 
    // set the properties on the Event object in the managedObjectContext. 

    Event *eventEntity = [NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:self.managedObjectContext]; 

    eventEntity.propertyA = event.propertyA; 
    eventEntity.propertyB = event.propertyB; 
    ... 
    [self.managedObjectContext save:&error]; 
} 

- (void) sendEvent:(Event *)event { 
    // send exact same event properties to remote server 
} 

(이벤트 NSManagedObject의 서브 클래스입니다).

대신 무엇을해야합니까? 내 NSManagedObject 객체와 동일한 속성/속성 인 을 가진 NSObject의 바닐라 서브 클래스를 생성해야합니까? 제안 된 솔루션은 NSInMemoryStoreType에 대한 이야기로 연결되었지만, 실제로 내가 원하는 모든 것이 객체를 전달하는 편리한 방법 일 때 잔인한 것으로 보입니다. 이 경우에는 객체가 NSManagedObject이므로, 내가 할 수있는 일이 제한적입니다.

+0

"이 문제가 발생했습니다"라고 말하면 정확히 무엇이 발생하고 있습니까? – Anomie

+0

'NSInvalidArgumentException'과 함께 실패합니다 : '- [Event setTimestamp :] : @syntehesize [d] 대신 모든 속성 @dynamic이 인스턴스 0x1c0d50으로 전송되었습니다. – djibouti33

답변

0

나는 얼마 전에 NSManagedObject에 범주를 작성하여 관리 대상의 표현을 NSDictionary으로 만듭니다. NSDictionary은 관리 대상 컨텍스트 외부에서 사용할 수 있습니다. 면책 조항 :이 코드는 철저히 테스트하지 않았으며 관리 대상 개체의 특성 만 처리하고 관계는을 처리하지 않습니다.

NSManagedObject+CLDAdditions.h 
------------------------------ 

@interface NSManagedObject (CLDAdditions) 
- (NSDictionary*)cld_dictionaryRepresentation; 
@end 

NSManagedObject+CLDAdditions.m 
------------------------------ 

@implementation NSManagedObject (CLDAdditions) 

- (NSDictionary*)cld_dictionaryRepresentation 
{ 
    // Create empty dictionary 
    NSMutableDictionary *objectDictionary = [NSMutableDictionary dictionary]; 
    // Set the entity 
    [objectDictionary setObject:[[self entity] name] forKey:@"entity"]; 
    NSDictionary *attributeKeys = [[self entity] attributesByName]; 
    // Go through each of the attributes and add them to the dictionary 
    for (NSString *attributeKey in attributeKeys) { 
     id attributeValue = [self valueForKey:attributeKey]; 
     if (attributeValue) { 
      // Supported objects 
      if ([attributeValue isKindOfClass:[NSNumber class]] || [attributeValue isKindOfClass:[NSString class]] || [attributeValue isKindOfClass:[NSNull class]] || [attributeValue isKindOfClass:[NSDate class]] || [attributeValue isKindOfClass:[NSData class]] || [attributeValue isKindOfClass:[NSURL class]]) { 
       [objectDictionary setObject:attributeValue forKey:attributeKey]; 
      // Unsupported objects 
      } else if ([attributeValue isKindOfClass:[NSDictionary class]] || [attributeValue isKindOfClass:[NSArray class]]) { 
       [NSException raise:NSGenericException format:@"Objects of type \"%@\" are not supported as Core Data attributes.", [attributeValue class]]; 
      // Transformable objects (conforming to NSCoding) 
      // TODO: Add support for custom value transformers 
      } else if (([[attributeKeys objectForKey:attributeKey] attributeType] == NSTransformableAttributeType) && [attributeValue conformsToProtocol:@protocol(NSCoding)]) { 
       NSData *attributeData = [NSKeyedArchiver archivedDataWithRootObject:attributeValue]; 
       [objectDictionary setObject:attributeData forKey:attributeKey]; 
      // Otherwise raise an exception 
      } else { 
       [NSException raise:NSGenericException format:@"Unsupported object type \"%@\". Objects must conform to the NSCoding protocol.", [attributeValue class]]; 
      } 
     } 
    } 
    return objectDictionary; 
} 

@end