I have Three tables, One to many relationship between Session and Album , One to many relationship between Album to songs , When I tried to fetch data from songs Then I get nothing
Here is my readFRomDB func
-(void)readDataFromDB{
AppDelegate *delegates = (AppDelegate *) [[UIApplication sharedApplication] delegate];
self.managedObjectContext = [delegates managedObjectContext];
if (runningSessionArray.count > 0) {
[runningSessionArray removeAllObjects];
}
NSManagedObjectContext *moc = [self managedObjectContext];
NSArray *searchResults = nil;
NSArray *searchAlbumsResults = nil;
NSArray *searchSongsResult=nil;
NSFetchRequest * fetchRequest1 = [[NSFetchRequest alloc] init];
NSFetchRequest * fetchRequest2 = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:#"RunningSession" inManagedObjectContext:moc];
NSFetchRequest *requestData = [[NSFetchRequest alloc] init];
[requestData setEntity:entityDescription];
[requestData setFetchLimit:1] ;
NSError *error;
// if get a entity, that means exists, so fetch it.
searchResults = [managedObjectContext executeFetchRequest:requestData error:&error];
for ( RunningSession *session in searchResults) {
// Update the Records
self.runnningSessionId=[NSString stringWithFormat:#"%#",session.runningSessionID];
self.title=session.title;
self.desc=[NSString stringWithFormat:#"%#",session.desc];
[fetchRequest1 setEntity:[NSEntityDescription entityForName:#"Albums"
inManagedObjectContext:session.managedObjectContext]];
[fetchRequest1 setEntity:entityDescription];
[fetchRequest1 setFetchLimit:1] ;
searchAlbumsResults = [session.managedObjectContext executeFetchRequest:fetchRequest1 error:&error];
NSMutableArray *tagNamesArray = [[NSMutableArray alloc] init];
//NSLog(#"Local Discount Shops:%#",discounts.shops);
NSSet *tagA = session.albums;
if (tagA.count>0) {
for (Albums *tag in tagA
) {
// NSLog(#"tag:%#",tag);
NSString *albumID;
NSString *aTitle;
NSString *aPrice;
NSString *aDuration;
NSString *aUrl;
NSString *aPurchasedHtml;
NSString *aNonPurchasedHtml;
if (tag.albumID != NULL) {
albumID = [NSString stringWithFormat:#"%#",tag.albumID]; //tag.shopId;
}else{
albumID = #"";
}
if (tag.title != NULL) {
aTitle = tag.title;
}
else{
aTitle = #"";
}
if (tag.price != NULL) {
aPrice = tag.price;
}
else{
aPrice = #"";
}
if (tag.duration != NULL) {
aDuration = tag.duration;
}
else{
aDuration = #"";
}
if (tag.url != NULL) {
aUrl = tag.url;
}
else{
aUrl = #"";
}
if (tag.purchasedHtml != NULL) {
aPurchasedHtml = tag.purchasedHtml;
}
else{
aPurchasedHtml = #"";
}
if (tag.nonPurchasedHtml != NULL) {
aNonPurchasedHtml = tag.nonPurchasedHtml;
}
else{
aNonPurchasedHtml = #"";
}
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:albumID,#"Id",aTitle,#"Title",aPrice,#"Price", aDuration,#"Duration",
albumUrl,#"Url",aPurchasedHtml,#"PurchasedItemsHtml",aNonPurchasedHtml,#"NonPurchasedItemsHtml", nil];
[tagNamesArray addObject:dict];
NSLog(#"tag.shop:%#",tag.songs);
[fetchRequest2 setEntity:[NSEntityDescription entityForName:#"Songs"
inManagedObjectContext:tag.managedObjectContext]];
[fetchRequest2 setEntity:entityDescription];
[fetchRequest2 setFetchLimit:1];
searchSongsResult = [tag.managedObjectContext executeFetchRequest:fetchRequest2 error:&error];
NSMutableArray *songsNamesArray = [[NSMutableArray alloc] init];
//NSLog(#"Local Discount Shops:%#",discounts.shops);
NSSet *tags = tag.songs;
if (tags.count>0) {
for (Songs *tag in tags) {
// NSLog(#"tag:%#",tag);
NSString *sID;
NSString *sTitle;
NSString *startTime;
if (tag.songsId !=NULL) {
sID = [NSString stringWithFormat:#"%#",tag.songsId]; //tag.shopId;
}else{
sID = #"";
}
if (tag.title != NULL) {
sTitle = tag.title;
}
else{
sTitle = #"";
}
if (tag.startTime != NULL) {
startTime = tag.startTime;
}
else{
startTime = #"";
}
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:sID,#"Id",sTitle,#"Title",startTime,#"Duration", nil];
[songsNamesArray addObject:dict];
}
}
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:albumID,#"Id",albumTitle,#"Title",albumPrice,#"Price",albumDuration,#"Duration",albumUrl,#"Url",albumPurchasedHtml,#"PurchasedItemsHtml",albumNonPurchasedHtml,#"NonPurchasedItemsHtml",songsNamesArray,#"Songs", nil];
}
}
// NSPredicate *bobPredicate = [NSPredicate predicateWithFormat:#"firstName = 'Bob'"];
// NSLog(#"Bobs: %#", [discounts filteredArrayUsingPredicate:bobPredicate]);
NSMutableArray *albumArray = [[NSMutableArray alloc] init];
albumArray = [tagNamesArray mutableCopy];
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:self.runnningSessionId,#"Id",title,#"Title",self.title,#"title",self.desc,#"Description",albumArray,#"Albums", nil];
[self.runningSessionArray addObject:dict];
// [self StudentDiscountData];
// NSLog(#"studentDataArray:%#",self.studentDataArray);
}
NSLog(#"RunningSession: %#",self.runningSessionArray);
}
I think you don't need to all those steps getting session data is enough and from that you can get Albums list as you set the one to many relationship. And from each Album you will get Songs
AppDelegate *delegates = (AppDelegate *) [[UIApplication sharedApplication] delegate];
self.managedObjectContext = [delegates managedObjectContext];
if (runningSessionArray.count > 0) {
[runningSessionArray removeAllObjects];
}
NSManagedObjectContext *moc = [self managedObjectContext];
NSArray *searchResults = nil;
NSArray *searchAlbumsResults = nil;// not required
NSArray *searchSongsResult=nil;//not required
NSFetchRequest * fetchRequest1 = [[NSFetchRequest alloc] init];//not required
NSFetchRequest * fetchRequest2 = [[NSFetchRequest alloc] init];//not required
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:#"RunningSession" inManagedObjectContext:moc];
NSFetchRequest *requestData = [[NSFetchRequest alloc] init];
[requestData setEntity:entityDescription];
[requestData setFetchLimit:1] ;
NSError *error;
// if get a entity, that means exists, so fetch it.
searchResults = [managedObjectContext executeFetchRequest:requestData error:&error];
//This returns array of sessions
for ( RunningSession *session in searchResults) {
NSArray *albumsArray = session.albums; //This returns Albums list as you set one to many relation
for ( Album *album in albumsArray) {
NSArray *songsArray = album.songs; //This returns songs list as you set one to many relation
}
}
Related
I am developing a chat app which needs contacts for chatting but when first time it is not showing the contacts again restart the app fetch then it is showing here is my code
-(NSMutableArray *)getAllContacts {
sleep(6);
// The user has previously given access, add the contact
ABRecordRef source = ABAddressBookCopyDefaultSource(addressBookRef);
CFArrayRef allPeople = (ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBookRef, source, kABPersonSortByFirstName));
CFIndex nPeople = ABAddressBookGetPersonCount(addressBookRef);
NSMutableArray* items = [[NSMutableArray alloc] init];
if (!allPeople || !nPeople) {
NSLog(#"people nil");
}
CFStringRef description = CFCopyDescription(allPeople);
NSLog(#"Array %#", description);
CFRelease(description);
for (int i = 0; i < nPeople; i++) {
// #autoreleasepool {
//data model
ContactsData *contacts = [ContactsData new];
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
//get First Name
CFStringRef firstName = (CFStringRef)ABRecordCopyValue(person,kABPersonFirstNameProperty);
contacts.firstNames = (__bridge NSString*)firstName;
if (firstName != NULL) {
CFRelease(firstName);
}
//get Last Name
CFStringRef lastName = (CFStringRef)ABRecordCopyValue(person,kABPersonLastNameProperty);
contacts.lastNames = (__bridge NSString*)lastName;
if (lastName != NULL) {
CFRelease(lastName);
}
if (!contacts.firstNames) {
contacts.firstNames = #"";
}
if (!contacts.lastNames) {
contacts.lastNames = #"";
}
contacts.contactId = ABRecordGetRecordID(person);
//append first name and last name
contacts.fullname = [NSString stringWithFormat:#"%# %#", contacts.firstNames, contacts.lastNames];
// get contacts picture, if pic doesn't exists, show standart one
CFDataRef imgData = ABPersonCopyImageData(person);
NSData *imageData = (__bridge NSData *)imgData;
contacts.image = [UIImage imageWithData:imageData];
if (imgData != NULL) {
CFRelease(imgData);
}
if (!contacts.image) {
contacts.image = [UIImage imageNamed:#"avatar.png"];
}
//get Phone Numbers
NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for(CFIndex i=0; i<ABMultiValueGetCount(multiPhones); i++) {
#autoreleasepool {
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
NSString *phoneNumber = CFBridgingRelease(phoneNumberRef);
phoneNumber = [[phoneNumber componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:#""];
if (phoneNumber != nil)[phoneNumbers addObject:phoneNumber];
//NSLog(#"All numbers %#", phoneNumbers);
}
}
if (multiPhones != NULL) {
CFRelease(multiPhones);
}
[contacts setNumbers:phoneNumbers];
//get Contact email
NSMutableArray *contactEmails = [NSMutableArray new];
ABMultiValueRef multiEmails = ABRecordCopyValue(person, kABPersonEmailProperty);
for (CFIndex i=0; i<ABMultiValueGetCount(multiEmails); i++) {
#autoreleasepool {
CFStringRef contactEmailRef = ABMultiValueCopyValueAtIndex(multiEmails, i);
NSString *contactEmail = CFBridgingRelease(contactEmailRef);
if (contactEmail != nil)[contactEmails addObject:contactEmail];
// NSLog(#"All emails are:%#", contactEmails);
}
}
if (multiPhones != NULL) {
CFRelease(multiEmails);
}
[contacts setEmails:contactEmails];
[items addObject:contacts];
#ifdef DEBUG
NSLog(#"Person is: %#", contacts.firstNames);
NSLog(#"Phones are: %#", contacts.numbers);
NSLog(#"Email is:%#", contacts.emails);
#endif
}
// } //autoreleasepool
CFRelease(allPeople);
CFRelease(addressBookRef);
CFRelease(source);
return items;
}
now i am getting the contacts and now i am fetching the contacts from
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController == nil)
{
NSManagedObjectContext *moc = [[self appDelegate] managedObjectContext_roster];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"XMPPUserCoreDataStorageObject"
inManagedObjectContext:moc];
NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:#"sectionNum" ascending:YES];
NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:#"displayName" ascending:YES];
NSArray *sortDescriptors = #[sd1, sd2];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setFetchBatchSize:20];
fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:moc
sectionNameKeyPath:#"sectionNum"
cacheName:nil];
[fetchedResultsController setDelegate:self];
NSError *error = nil;
if (![fetchedResultsController performFetch:&error])
{
DDLogError(#"Error performing fetch: %#", error);
NSLog(#"Error performing fetch");
}
}
return fetchedResultsController;
}
now assigning this fetched controller to array like
self.UserArray=[[[self fetchedResultsController] fetchedObjects] mutableCopy];
but unable to fetch the contacts to tableview where i miss please help me out
I am developing iOS app, which fetch data from Web Services and save it to local database and uses it various views as needed. The data is fetch from Web Service and save to database correctly. But while accessing data from NSManagedObject it show FAULT and the consequent NSDictionary shows null Values
The code follows:-
-(void)SaveData:(NSInteger)menuId categoryID:(NSInteger)catID caption:(NSString *)title parentID:(NSInteger)parentID
{
BBAppDelegate *appDelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *userobj = [NSEntityDescription insertNewObjectForEntityForName:tableName
inManagedObjectContext:context];
[userobj setValue:[NSNumber numberWithInt:menuId] forKey:#"id"];
[userobj setValue:[NSNumber numberWithInt:catID] forKey:#"catid"];
[userobj setValue:[NSNumber numberWithInt:parentID] forKey:#"parentid"];
[userobj setValue:title forKey:#"caption"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
NSLog(#"app dir: %#",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
}
-(NSArray *)fetchedData{
BBAppDelegate *appdelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appdelegate managedObjectContext];
NSFetchRequest *readData = [[NSFetchRequest alloc] init];
[readData setReturnsObjectsAsFaults:NO];
NSEntityDescription *entity = [NSEntityDescription
entityForName:tableName inManagedObjectContext:context];
[readData setEntity:entity];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:readData error:&error];
// for (Test *test in array)
// {
// NSLog(#"Test: %# ", test.text);
// }
NSLog(#"%#",results);
return results;
}
-(void)removeData{
BBAppDelegate *appdelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appdelegate managedObjectContext];
NSFetchRequest *delData = [[NSFetchRequest alloc]init];
[delData setEntity:[NSEntityDescription entityForName:tableName inManagedObjectContext:context]];
[delData setIncludesPropertyValues:NO];
NSError *error = nil;
NSArray *result = [context executeFetchRequest:delData error:&error];
for (NSManagedObject *value in result) {
[context deleteObject:value];
}
NSError *saveError = nil;
[context save:&saveError];
}
-(void)table:(NSString *)nameTable{
tableName =nameTable;
}
- (instancetype)initWithTableName:(NSString *)tablename
{
[self table:tablename];
return self;
}
-(NSMutableArray *)buldMenu{
NSArray *array = [self fetchedData];
return [self getmenus:0 arr:array];
}
-(NSMutableArray *)getmenus:(NSInteger)parentID arr: (NSArray *)array
{
NSMutableArray *aray = [[NSMutableArray alloc]init];
for (NSManagedObject *dic in array) {
if (dic.faultingState != 0) {
NSLog(#"%lu",(unsigned long)dic.faultingState);
//return nil;
}
NSArray *keys = [[[dic entity] attributesByName] allKeys];
NSLog(#"%#",keys);
NSDictionary *dict = [dic dictionaryWithValuesForKeys:keys];
NSLog(#"%#",dic);
NSLog(#"%#",dict);
NSInteger pID = [[dict objectForKey:#"parentid"]integerValue];
if (pID == parentID) {
BBMenuEntry *entryMenu = [[BBMenuEntry alloc]init];
entryMenu.menuID = [[dict objectForKey:#"id"]integerValue];
entryMenu.catID = [[dict objectForKey:#"catid"]integerValue];
entryMenu.caption = [dict objectForKey:#"caption"];
entryMenu.subMenus = [self getmenus:entryMenu.menuID arr:array];
[aray addObject:entryMenu];
}
}
return aray;
}
I'm trying to update certain currency abbreviations in the coredata with this function.
- (void)updateCurrencies
{
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"Transaction" inManagedObjectContext:managedObjectContext]];
NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];
NSLog(#"Number of data : %lu", (unsigned long)[results count]);
for (int i = 0; i < [results count]; i++) {
Transaction* t = [results objectAtIndex:0];
NSLog(#"currency: %#", t.currency);
if ([t.currency isEqualToString:#"CAN"]) {
t.currency = #"CAD";
NSLog(#"new currency set.");
}
[self saveContext];
}
}
}
I call this function in didFinishLaunchingWithOptions. Now, the log does inform me that t.currency has been updated to CAD. However when I retrieve the data again in HomeViewController and log the currency, it is back to CAN. This is the code in HomeViewController,
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *transaction = [NSEntityDescription entityForName:#"Transaction" inManagedObjectContext:_managedObjectContext];
[request setEntity:transaction];
request.predicate = [NSPredicate predicateWithFormat:#"transactionToUser = %#", [self.content objectAtIndex:i]];
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"postdate" ascending:NO];
NSArray *descriptors = [[NSArray alloc] initWithObjects:descriptor, nil];
[request setSortDescriptors:descriptors];
NSError *error = nil;
NSMutableArray *mutableResult = [[_managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableResult == nil) {
//handle error
}
for (int k = 0; k < [mutableResult count]; k++) {
Transaction *t = [mutableResult objectAtIndex:k];
NSLog(#"currency xx: %#", t.currency);
}
What am I doing wrong? Any help is appreciated. Thanks.
Fixed it with a different for loop.
for (Transaction *t in results)
{
...
}
I am parsing data from JSON and Storing to CoreData in the same time i am displaying the the data to tableview but the problem i am having is data is displaying only after download completed but i dont want like this i want to download the data in background and display the data while downloading is processed also how can i do this
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
arrayData = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSError *error;
NSManagedObjectContext *context = [appDelegate managedObjectContext];
context = [appDelegate managedObjectContext];
for (int i = 0; i < [arrayData count]; i++) {
idNum = [arrayData objectAtIndex:i][#"id"];
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Discount"];
[request setPredicate:[NSPredicate predicateWithFormat:#"cID = %#",idNum]];
[request setFetchLimit:1];
NSUInteger count = [context countForFetchRequest:request error:&error];
if (count == NSNotFound) {
NSLog(#"ERROR");
}else if (count == 0) {
NSLog(#"New Data Coming");
name = [arrayData objectAtIndex:i][#"name"];
summary = [arrayData objectAtIndex:i][#"summary"];
region = [arrayData objectAtIndex:i][#"region"];
imageURL = [arrayData objectAtIndex:i][#"images"][#"logo"];
id benefits1 = [arrayData objectAtIndex:i][#"benefits"];
benefiteString = [NSString stringWithFormat:#"%# %#",[benefits1 objectAtIndex:0][#"key"],[benefits1 objectAtIndex:0][#"value"]];
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
dateUpdate = [arrayData objectAtIndex:i][#"updated_at"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat: #"yyyy-MM-dd'T'HH:mm:ss.sssZ"];
NSDate *date =[dateFormatter dateFromString:dateUpdate];
[dateFormatter setDateFormat:#"yyyy/MM/dd HH:mm:ss"];
NSLog(#"DAte : %#",date);
Discount * d = [NSEntityDescription insertNewObjectForEntityForName:#"Discount" inManagedObjectContext:context];
d.name = name;
d.summary = summary;
d.regions = region;
d.cID = idNum;
d.imageLogo = data;
d.updated_at = date;
d.benefits = benefiteString;
if (![context save:&error]) {
NSLog(#"Getting error while saving data");
}
else{
NSLog(#"Saved");
}
}
}
[sharedAppDelegate dismissGlobalHUD];
[listTableView reloadData];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_myArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
customCellClass = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (customCellClass == nil)
{
customCellClass = [[CellCustom alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
}
customCellClass.nameLabel.text = [[_myArray objectAtIndex:indexPath.row]name];
customCellClass.cityLabel.text =[[_myArray objectAtIndex:indexPath.row]regions];
customCellClass.detailLabel.text = [[_myArray objectAtIndex:indexPath.row]summary];
NSData * d = [[_myArray objectAtIndex:indexPath.row]imageLogo];
customCellClass.mainImage.image = [UIImage imageWithData:d];
customCellClass.benefitsLabel.text = [[_myArray objectAtIndex:indexPath.row]benefits];
[sharedAppDelegate dismissGlobalHUD];
return customCellClass;
}
-(void)dataDidSave
{
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Discount" inManagedObjectContext:context]; [fetchRequest setEntity:entity];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *result = [context executeFetchRequest:fetchRequest error:&error];
self.myArray = result;
[listTableView reloadData];
}
-(void)viewWillAppear:(BOOL)animated
{
[sharedAppDelegate showGlobalProgressHUDWithTitle:#"Loading..."];
[self dataDidSave];
}
In connectionDidFinishLoading: try something like this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^ {
// Process your data and then incrementally call
dispatch_async(dispatch_get_main_queue(),^ {
[listTableView reloadData];
});
}
});
I am a beginner in Xcode. I would like to get the username or the ID after the user enters their login and password in textfield. I am sure I am doing wrong.
My code bug is after the access granted.
app due to uncaught exception
'`NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]:
object cannot be nil`'
Here is my code:
- (IBAction)stepInButton:(id)sender {
AppDelegate *appDelegateCoreData = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegateCoreData managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"Player" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:
#"(playerlogin = %#) AND (playerpassword =%#)", self.loginTextField.text, self.passwordTextField.text];
[request setPredicate:pred];
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if ([objects count] == 0) {
self.loginStatusLabel.hidden = NO;
NSLog(#"LOGIN IN ACCESS DENIED");
} else {
NSLog(#"LOGIN IN ACCESS GRANTED");
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:#"playerfirstname"];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setExpression:keyPathExpression];
[expressionDescription setExpressionResultType:NSDateAttributeType];
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if ([objects count] == 0) {
// Handle the error.
}
else {
if ([objects count] > 0) {
NSString *playerFirstName = [[objects objectAtIndex:0] valueForKey:#"playerfirstname"];
NSLog(#"PlayerFirstName: %#", [[objects objectAtIndex:0] valueForKey:#"playerfirstname"]);
self.welcomePlayerLabel.text = [NSString stringWithFormat: #"Welcome %#", playerFirstName];
}
}
self.loginStatusLabel.hidden = YES;
self.signButton.hidden = YES;
self.stepButton.hidden =YES;
self.loginStatusLabel.text =(#"Access Granted");
self.loginStatusLabel.textColor = [UIColor greenColor];
self.loginStatusLabel.hidden = NO;
//FirstViewController *firstViewController = [[FirstViewController alloc] init];
//[self.navigationController pushViewController:firstViewController animated:YES];
//[self.navigationController pushViewController:[self.storyboard instantiateViewControllerWithIdentifier:#"first"] animated:YES];
}
}
ok I got it.
I retieved the playerFirstName directly form object like Dan Shelly said. Thanks you Dan.
- (IBAction)stepInButton:(id)sender {
AppDelegate *appDelegateCoreData = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegateCoreData managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"Player" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:
#"(playerlogin = %#) AND (playerpassword =%#)", self.loginTextField.text, self.passwordTextField.text];
[request setPredicate:pred];
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if ([objects count] == 0) {
self.loginStatusLabel.hidden = NO;
NSLog(#"LOGIN IN ACCESS DENIED");
} else {
NSLog(#"LOGIN IN ACCESS GRANTED");
NSString *playerFirstName = [[objects objectAtIndex:0] valueForKey:#"playerfirstname"];
self.welcomePlayerLabel.text = [NSString stringWithFormat: #"Welcome %#", playerFirstName];
self.loginStatusLabel.hidden = YES;
self.signButton.hidden = YES;
self.stepButton.hidden =YES;
self.loginStatusLabel.text =(#"Access Granted");
self.loginStatusLabel.textColor = [UIColor greenColor];
self.loginStatusLabel.hidden = NO;
}
}