2012-12-13 1 views
0

나는 그것의 유일한 객체에 의해 객체를 가져 오려고하는데, 그 객체를 가져 오기 위해 객체를 삽입하는 ID를 저장하려고합니다. 여기에 내 코드가 있습니다.문제 속성으로 사용할 때 NSManagedObjectID 함께

@implementation UserInfoDOA 
@synthesize firstName,lastName,userName,bDate,department,searchByDept,searchByName,moid,uriData,uri; 

- (NSString *)insertUser 
{  
    UserInfoAppDelegate *delegate = (UserInfoAppDelegate *)[[UIApplication sharedApplication] delegate]; 
    UserInfo *newUser = [NSEntityDescription insertNewObjectForEntityForName:@"UserInfo" 
            inManagedObjectContext:delegate.managedObjectContext]; 


    Department *dept = [NSEntityDescription insertNewObjectForEntityForName:@"Department" 
                inManagedObjectContext:delegate.managedObjectContext]; 

    moid = [newUser objectID]; 
    NSLog(@"IN INSERTUSER %@", moid); // moid displays its value 

    if(dept!=nil) { 
     [email protected]"1001"; 
     dept.name=department; 
     [email protected]"ahmedabad"; 
     [email protected]"developer";   
    } 

    if (newUser != nil) { 
     newUser.firstName =firstName; 
     newUser.lastName =lastName; 
     newUser.userName=userName; 
     newUser.bDate = bDate ; 
     newUser.dept=dept; 

     NSError *savingError = nil; 

     if ([delegate.managedObjectContext save:&savingError]) { 
      NSLog(@"Successfully saved the context."); 
     } 
     else {  
      NSLog(@"Failed to save the context. Error = %@", savingError); 
     } 
    } 
    else {   
     NSLog(@"Failed to create the new person."); 
    } 

    NSLog(@"IN INSERTUSER after %@",moid); 

    return @"true"; 
} 

- (NSArray *) getUser 
{ 
    NSLog(@"IN GETUSER %@", moid); //NOT WORKING, moid is NULL here 

    UserInfoAppDelegate *delegate = (UserInfoAppDelegate *)[[UIApplication sharedApplication] delegate]; 


    NSEntityDescription *entity = [NSEntityDescription entityForName:@"UserInfo" 
               inManagedObjectContext:delegate.managedObjectContext]; 

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
    [fetchRequest setEntity:entity]; 


    NSPredicate *predicate=[NSPredicate predicateWithFormat:@"(objecId = %@)",moid]; 


    [fetchRequest setPredicate:predicate]; 

    NSError *requestError = nil; 
    NSArray *users = [delegate.managedObjectContext executeFetchRequest:fetchRequest      
                    error:&requestError]; 

    return users;  
} 

그래서 무엇이 잘못 되었나요? 나는 속성으로 저장했지만 제 두 번째 함수에서 moid에 액세스 할 수 없습니다.

답변

1

우선 ARC를 사용하고 있습니까, 그렇지 않은가요?

그런 다음이 이유가 무엇입니까?

- (NSString *)insertUser 
{ 
    // other code here 

    return @"true" 
} 

사용이 대신

- (BOOL)insertUser 
{ 
    // other code here 

    return YES // or NO based on the insertion result 
} 

그런 다음, 당신이 NSManagedObjectID에 의존해서는 안, 귀하의 질문에 대해

- (UserInfo *)getUser 
{ 
    // other code here 

    // maybe you should add some code for error handling...you haven't set up any code there... 
    return [users objectAtIndex:0]; 
} 

이 메소드

- (NSArray *)getUser 

를 사용합니다. MarcusS.Zarra @으로

가 NSManagedObjectID이 일관성을 보장 할 수 없습니다 제안했다. 데이터 이전 및 기타 요소를 포함한 여러 요인에 따라 을 변경할 수 있습니다. 이것을 객체 인 의 고유 식별자로 사용하는 경우 중지하십시오.

그래서, UserInfo 엔티티 (A NSString가 확인 될 수있다) 모델의 속성을 추가하고 사용자를 검색 할 때 새 사용자를 만들 때 설정합니다.

self.moid = [newUser userIdentifier]; 

당신이 CORE DATA objectId changes constantly에서 살펴하거나 생성하기위한 자신 만의 알고리즘을 만들 수있는 새로운 식별자를 만들려면 지금처럼 moid will be

@property (nonatomic, copy) NSString* moid; // also synthesize it (optional) 

설정됩니다

// insert 
user.userIdentifier = // your identifier 

// retrieve 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(userIdentifier == %@)", self.moid]; 

.

P. 나는 컴파일러가 newUser에 대해 불평 할 것이기 때문에 ARC를 사용하지 않는 것으로 생각한다.

+0

예 ARC가 활성화 된 환경에서 작업하고 있습니다. 고유 ID를 저장하려고하고 나중에 업데이트 목적으로이 ID를 사용하여 객체를 가져 오려고했습니다. – BaSha

0

개체 ID에는 두 가지 형식이 있습니다. 관리 대상 개체를 처음 만들 때 Core Data는 임시 ID를 할당합니다. 영구 저장소에 저장되는 경우에만 코어 데이터가 관리 대상에 영구 ID를 할당합니다. 당신은 쉽게 ID를 임시인지 발견 할 수 있습니다 :

BOOL isTemporary = [[managedObject objectID] isTemporaryID]; 

그것은 개체의 사용자 ID가 컨텍스트를 저장 한 후 가능한 변화지고 수 있음.

+0

NULL을 제공하는 newUser를 저장 한 후 확인했습니다! BOOL isTemporary = [[newUser objectID] isTemporaryID]; NSLog (@ "IS TEMP : % @", isTemporary); – BaSha

+0

실제로 % @가 참조 할 때 개체를 인쇄하는 데 사용됩니다. 그래서 NSLog (@ "IS TEMP : % @", isTemporary); 잘못된 것입니다. No는 0을 반환하고 Null은) 주소를 찾습니다. –

+0

isTemprory가 NO를 반환하고 있음을 의미합니다. –

관련 문제