我想通過它的唯一對象獲取對象,爲此我保存了插入對象的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
。
是的,我正在ARC支持的環境中工作,我正在嘗試保存唯一的ID,後來爲了更新目的使用該ID獲取對象。 – BaSha