convert parse to image in nsarray - ios

Can anyone please help me here? scenario is:
I have a view controller, page view controller, and a content for page view controller.
The app is to initially load 3 pages of images, and on the 3rd page a button will then appear. if pressed it'll be directed to the main menu page.
all images are loaded from parse.
I previously had a separate program for page view controller and another for parse image loader, executed perfectly. however when I combine both together it fails. based on what I understand is that, images from parse are stored as NSData. however, in my page view controller, i'm using index to load the images. I tried converting NSData to NSArray using KeyedAchiver however it couldn't work.
I also notice that my image loaded from parse doesn't come in the sequence I want. So, if possible, please help to advise on this!
below are the codes. thanks in advance!
//***********************view controller
#import "ViewController.h"
#import <parse/parse.h>
#interface ViewController ()
#end
#implementation ViewController
#synthesize parseImageData,pageImages; //UIImage, NSData
- (void)viewDidLoad
{
[super viewDidLoad];
// Create the data model
// _pageTitles = #[#"New York Cheese", #"Vanilla Cake", #"Green Tea Cake", #"Choc Indulgence"];
// _pageImages = #[#"pic1.png", #"pic2.png", #"pic3.png", #"pic4.png"];
_pageTitles = #[#"New York Cheese", #"Vanilla Cake"];
// Create page view controller
self.pageViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"PageViewController"];
self.pageViewController.dataSource = self;
PageContentViewController *startingViewController = [self viewControllerAtIndex:0];
NSArray *viewControllers = #[startingViewController];
[self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
// Change the size of page view controller
self.pageViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 30);
[self addChildViewController:_pageViewController];
[self.view addSubview:_pageViewController.view];
[self.pageViewController didMoveToParentViewController:self];
NSLog(#"viewcontroller.m viewdidload complete");
}
- (PageContentViewController *)viewControllerAtIndex:(NSUInteger)index
{
if (([self.pageTitles count] == 0) || (index >= [self.pageTitles count])) {
NSLog(#"out of range!");
return nil;
}
NSLog(#"viewcontroller.m update index");
//add my own parse program
PFQuery *query = [PFQuery queryWithClassName:#"Pictures"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error){
NSLog(#"picture queried");
NSLog(#"array %#",objects);
NSArray *imageFilesArray = [[NSArray alloc]initWithArray:objects];
PFObject *imageObject = [imageFilesArray objectAtIndex:index];
PFFile *imageFile = [imageObject objectForKey:#"imageFile"];
// scrolling.hidden = NO;
// [scrolling startAnimating];
NSLog(#"pffile %#",imageFile);
[imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if(!error){
// scrolling.hidden = YES;
//imageView.image = [UIImage imageWithData:data];
pageImages = data;
parseImageData = [UIImage imageWithData:data];
NSLog(#"nsdata translated %#",parseImageData);
// pageContentViewController.imageFile = data;
}
}];
}}];
// Create a new view controller and pass suitable data.
PageContentViewController *pageContentViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"PageContentViewController"];
// pageContentViewController.imageFile = self.pageImages[index];
pageContentViewController.titleText = self.pageTitles[index];
NSLog(#"self.pagetitles[index]");
//pageContentViewController.imageFile = parseImageData;
NSArray *pageImagesArray = [NSKeyedArchiver archivedDataWithRootObject:pageImages];
pageContentViewController.imageFile = pageImagesArray[index];
NSLog(#"pagecontentviewcontroller.imagefile is %#",pageContentViewController.imageFile);
NSLog(#"self.parseImageData %lu",(unsigned long)index);
pageContentViewController.pageIndex = index;
return pageContentViewController;
}
//*****************PAGE CONTENT CONTROLLER PART
#import "PageContentViewController.h"
#import <parse/parse.h>
#interface PageContentViewController ()
#end
#implementation PageContentViewController
#synthesize imageFile,titleText,backgroundImageView; //NSData, NSString, IBOutlet UIImage
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//self.backgroundImageView.image = [UIImage imageWithData:imageFile];
backgroundImageView.image = [UIImage imageWithData:imageFile];
self.titleLabel.text = self.titleText;
NSLog(#"Image supposed be loaded...%#",imageFile);
NSLog(#"title supposed be loaded...%#",titleText);
}

Related

Load photos to DetailViewController from NSMutableArray

I'm new to iOS development and am currently studying from video tutorials. I came across a problem with quite a simple app I'm experimenting on.
The problem is with loading pictures to UIImage in a split view control iPad app. The app is based on the XCode master-detail application template. I created an array with NSObject variables and two properties.
#interface Burger : NSObject
#property (nonatomic) NSString *name;
#property (nonatomic) NSString *filename;
#end
- (void)viewDidLoad {
[super viewDidLoad];
photos = [[NSMutableArray alloc]init];
Burger *pic = [[Burger alloc]init];
pic.name = #"Bacon";
pic.filename = #"burger-bacon";
[photos addObject:pic];
pic = [[Burger alloc]init];
pic.name = #"Cheese";
pic.filename = #"burger-cheddar";
[photos addObject:pic];
pic = [[Burger alloc]init];
pic.name = #"Hawaii";
pic.filename = #"burger-hawaii";
[photos addObject:pic];
pic = [[Burger alloc]init];
pic.name = #"Koko z jajkiej kurzym";
pic.filename = #"burger-jajo";
[photos addObject:pic];
pic = [[Burger alloc]init];
pic.name = #"Kozi ser";
pic.filename = #"burger-kozi";
[photos addObject:pic];
pic = [[Burger alloc]init];
pic.name = #"Łosoś";
pic.filename = #"burger-losos";
[photos addObject:pic];
pic = [[Burger alloc]init];
pic.name = #"Vege (Soczewica)";
pic.filename = #"burger-soczewica";
[photos addObject:pic];
}
I want the UImageView nested in DetailView to display a picture of the object chosen in the MasterView controller. I got it to display the pictures in the MasterView table
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
Burger *current = [photos objectAtIndex:indexPath.row];
UIImage *image = [UIImage imageNamed:[current filename]];
[cell.imageView setImage:image];
self.title = self.currentPhoto.name;
cell.textLabel.text = [current name];
cell.detailTextLabel.text = [current price];
return cell;
}
and it also works when I point to a specific file name:
- (void)configureView {
// Update the user interface for the detail item.
if (self.detailItem) {
self.detailDescriptionLabel.text = [self.detailItem notes];
UIImage *image = [UIImage imageNamed: #"burger-bacon"];
[self.currentImage setImage:image];
self.title = self.currentPhoto.name;
}
}
but when I try to show the picture of the chosen element like this:
- (void)configureView {
// Update the user interface for the detail item.
if (self.detailItem) {
self.detailDescriptionLabel.text = [self.detailItem notes];
UIImage *image = [UIImage imageNamed: self.currentPhoto.filename];
[self.currentImage setImage:image];
self.title = self.currentPhoto.name;
}
}
I get these few lines in the debug area:
2015-06-23 12:13:25.964 SlowFoodiPad[22177:744765] CUICatalog: Invalid asset name supplied: (null)
which means the segues work and the photo files seem to be fine. There seem to be a problem with pointing to the right file to display. Any ideas how to fix it?
OK, I managed to solve the problem partially. I edited prepareForSegue method of MasterViewController:
DetailViewController *controller = (DetailViewController *)[[segue destinationViewController] topViewController];
Burger *c = photos [indexPath.row];
[controller setDetailItem:c];
//this line helped
[controller setCurrentPhoto:c];
The appropriate photos now show, although the debug area keeps showing me this message:
CUICatalog: Invalid asset name supplied: (null)
two identical lines each time I tap on an element in the MasterView table.
Right now it's unclear when "-(void)configureView" is being called. My guess, based on your issue, is that it's actually called before prepareForSegue. Or at least, the very first time, it's being called before you actually have an image. You are checking for "if (self.detailItem)" but you are not checking for if (self.currentPhoto).
So probably the first time configure view is called, there is no self.currentPhoto so it can't be set. Then when the segue is actually prepared (prepareForSegue:) you set the current photo, so then when configure view is called again, it's there.
If you paste more of your view controller code that shows what triggers the segue (probably it's just the storyboard but unclear from what you have above) and when configureView, then we'd know for sure if my guess is correct.
OK, there's some progress. Now I only get two lines of this message and only at initial start of the app:
CUICatalog: Invalid asset name supplied: (null)
I commented out few lines here. Can you see anything else that is causing problems?
- (void)setDetailItem:(id)newDetailItem {
if (_detailItem != newDetailItem) {
_detailItem = newDetailItem;
// Update the view.
[self configureView];
}
}
- (void)configureView {
// Update the user interface for the detail item.
// if (self.detailItem) {
self.detailDescriptionLabel.text = [self.detailItem notes];
// UIImage *image = [UIImage imageNamed:self.currentPhoto.filename];
// [self.currentImage setImage:image];
}
//}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIImage *image = [UIImage imageNamed:self.currentPhoto.filename];
[self.currentImage setImage:image];
self.title = self.currentPhoto.name;
self.detailDescriptionLabel.text = [self.detailItem notes];
// [self configureView];
}
Here's the prepareForSegue method:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"showDetail"]) {
DetailViewController *controller = (DetailViewController *)[[segue destinationViewController] topViewController];
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
Burger *c = photos [indexPath.row];
[controller setDetailItem:c];
//adding this line helped
[controller setCurrentPhoto:c];
controller.navigationItem.leftBarButtonItem = self.splitViewController.displayModeButtonItem;
controller.navigationItem.leftItemsSupplementBackButton = YES;
}
}

UIPageViewController does not show its view controllers views

I have a UIPageViewController in a UIViewController , I am having a problem where the pageviewcontroller's inner view are not shown [Although I am sure they are loaded from the server]!
Some helpful notes:
UIPageViewController (called :pageController)
Outer UIViewController (called :OfferDetailsViewController)
each viewController inside the pageController is of type OfferBannerPageViewController
Here is my code related to the problem , Please ask for any other blocks of code if you think it will help finding the problem source
some of :OfferDetailsViewController.m :
- (void)viewDidLoad {
[super viewDidLoad];
delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
if(_offerId)
{
_offer = [[Offer alloc]init];
[delegate setUpAConnectionToGetADetailedOffer:_offerId];
//first: load the offer
[self loadOffer];
[self startTimer];
}
}
-(void) loadOffer{
NSMutableString * pathPattern = [NSMutableString stringWithString: #"api/Offers/"];
[pathPattern appendString:_offerId];
[[RKObjectManager sharedManager]getObjectsAtPath:pathPattern parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
if(mappingResult){
_offer = (Offer *)[mappingResult.array firstObject];
//second load the offer banners images
[self setOfferView];
dispatch_async(dispatch_get_main_queue(), ^{
[self loadOfferBanners];
});
}else{
}
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
}];
}
-(void)loadOfferBanners {
_offer.OfferPannerImagesObjects = [[NSMutableArray alloc]init];
for(int index = 0 ; index<_offer.OfferPannerImages.count ;index++){
NSURL *imageURL =[NSURL URLWithString:_offer.OfferPannerImages[index]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
//[UIImage imageWithData:imageData];
if(image){
[_offer.OfferPannerImagesObjects addObject: image];
}
}
if(_offer.OfferPannerImagesObjects.count>0){
[self setUpOfferBanners];
}
}
-(void)setUpOfferBanners {
self.pageController = [[UIPageViewController alloc]initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
self.pageController.dataSource = self;
CGRect rect = [self.pagesView bounds];
[[self.pageController view] setFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
OfferBannerPageViewController * initialBanner = [self viewControllerAtIndex: 0];
[self.pageController setViewControllers:[NSArray arrayWithObjects:initialBanner, nil] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil ];
[self addChildViewController:self.pageController];
[[self pagesView] addSubview:[self.pageController view]];
[self.pageController didMoveToParentViewController:self];
self.pagesView.clipsToBounds=YES;
self.pagesView.layer.cornerRadius= 6;
}
here is the ViewControllerAtIndex method I debug it and found that index is always whereas when I hover in it after stopping at a break point I see its value as 0!
- (OfferBannerPageViewController *)viewControllerAtIndex:(NSUInteger)index {
OfferBannerPageViewController *offerBannerPageViewController = [[OfferBannerPageViewController alloc] initWithNibName:#"OfferBannerPageViewController" bundle:nil];
offerBannerPageViewController.bannerView = _offer.OfferPannerImagesObjects[index];
offerBannerPageViewController.index = [NSNumber numberWithLong:(long)index];
NSLog(#"____________________ [INDEX = %ld] ___________________",(long)index);
[offerBannerPageViewController.bannerView setImage:_offer.OfferPannerImagesObjects[index]];
return offerBannerPageViewController;
}
any help will be extremely appreciated, Thank you.
update
- (NSInteger)presentationCountForPageViewController: (UIPageViewController*)pageViewController {
// The number of items reflected in the page indicator.
return [_offer.OfferPannerImages count];
}
- (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController {
// The selected item reflected in the page indicator.
return 0;
}
-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController{
NSInteger index = (long)((OfferBannerPageViewController *)viewController).index;
if(index >= _offer.OfferPannerImagesObjects.count){
return nil;
}
index ++;
return [self viewControllerAtIndex:index];
}
-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
NSInteger index = (long)((OfferBannerPageViewController *)viewController).index;
if(index == 0)
return nil;
index--;
return [self viewControllerAtIndex:index];
}
update 2: OfferBannerPageViewController.h
#interface OfferBannerPageViewController : UIViewController
#property (strong,nonatomic) NSNumber * index;
#property (strong,nonatomic)IBOutlet UIImageView * bannerView;
#end
Not sure about this, but maybe you should use autoresizing masks to make sure OfferBannerPageViewController's view resizes width and height along with the superview. It might happen that when you set the frame of pageController.view based on bounds of superview, the bounds are 0 width and height and then doesn't resize.
So try:
[[self.pageController view] setFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
[[self.pageController view] setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
Have you implemented presentationCountForPageViewController, presentationIndexForPageViewController, viewControllerBeforeViewController and viewControllerAfterViewController methods?
Please, show them.

don't display image in UIScrollView

I created 2 class (RecipeViewController & DetailViewController)
RecipeView is TableViewController that show me 4 cell (name of book) and DetailView is UIViewController that has UIScroll that show me many images of any book.
my problem is when I click on any cell and go to next page UIScroller dont show images to me.
this is my code:
RecipeViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int x = (indexPath.row)+1;
NSLog(#"x : %d",x);
DetailViewController *obj = [[DetailViewController alloc]init];
obj.yourValue = [NSString stringWithFormat:#"%d",(indexPath.row)+1];
[self presentModalViewController:obj animated:YES];
NSLog(#"yourValue1 : %#",obj.yourValue);
}
DetailViewController.m
#import "DetailViewController.h"
#import "RecipeViewController.h"
#implementation DetailViewController
#synthesize scroller,yourValue;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//m1 variable tell me in tableview which choice book
int m1 = [self.yourValue integerValue];
NSLog(#"m1 : %d",m1);
//this code give me number of images (pages of book)
NSString *numberbook = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.1.102/mamal/book.php?info=0&b=%d",m1]]];
NSInteger numbook = [numberbook integerValue];
NSLog(#"%d",numbook);
for (int i = 1; i <= numbook; i++)
{
//this code for recive images from specific book
NSData *dat = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.1.102/mamal/book.php?p=%d&b=%d",i,m1]]];
NSLog(#"%#",dat);
UIImageView *imagen = [[UIImageView alloc] initWithImage:[UIImage imageWithData:dat]];
imagen.frame = CGRectMake((i-1)*320, 0, 320, 460);
[scroller addSubview:imagen];
}
scroller.delegate = self;
scroller.contentSize = CGSizeMake(320*numbook, 460);
scroller.pagingEnabled = YES;
}
#end
sorry for my weak english!!!
If you really want to use [NSData dataWithContentsOfURL:]; Add this inside your loop, chnage url and the imageView frame.
for (int i = 1; i <= numbook; i++)
{
UIImageView *yourImage=[[UIImageView alloc]init];
yourImage.frame = CGRectMake((i-1)*320, 0, 320, 460);
[scroller addSubview:imagen];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.1.102/mamal/book.php?p=%d&b=%d",i,m1]];
NSData *imgData = [NSData dataWithContentsOfURL:url];
dispatch_sync(dispatch_get_main_queue(), ^{
UIImage *downloadedImage = [UIImage imageWithData:imgData];
yourImage.image = downloadedImage;
if(yourImage.image==nil)
{
[yourImage setImage:#"placeholder.png"];
}
});
});
}
Hey you are doing everything in the main thread and there can be a delay or some other problems generally it is not advised to do so , can you make use of NickLockWoods implementation for loading images asynchronously
https://github.com/nicklockwood/AsyncImageView
It is a very good category of UIImageView, you just have to import AsyncImageView and can use the function
[imageView setImageURL:#"ur url"];
It loads up all images asynchronously and it has so many customizations.
In your case:
for (int i = 1; i <= numbook; i++)
{
UIImageView *imagen = [[UIImageView alloc] initWithFrame: CGRectMake((i-1)*320, 0, 320, 460)];
[imagen setImageURL: [NSString stringWithFormat:#"192.168.1.102/mamal/book.php?p=%d&b=%d",i,m1]]];
[scroller addSubview:imagen];
}
You are doing everything in the main thread, that is why it is not loading images. In the same code that you are doing try giving background color of imageView and check.

setting / retrieving data from singleton

Apple rejected our app siting that page loads times between tabs was too long. Before I was simply calling a webview to display content managed through a CMS. Now we have implemented JSON and I am tring to preload the 5 tabs' data using the singleton design pattern. I can't seem to set the singleton value as I see in examples. On to the code:
header.h
#import <UIKit/UIKit.h>
#interface FirstViewController : UIViewController {
NSString *someProperty;
...
}
#property (nonatomic, retain) NSString *someProperty;
+ (id)sharedManager;
#property (strong, nonatomic) NSString* tab3data;
#end
Implementation.m
//Create a seperate thread to download JSON thread
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
//Set JSON URL
#define GWDiOSURL [NSURL URLWithString:#"http://m.web.org/cms_mapper.php"]
#import "FirstViewController.h"
#interface FirstViewController ()
#end
#implementation FirstViewController
#synthesize someProperty;
- (id)init {
if (self = [super init]) {
someProperty = #"Default Property Value";
}
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"First", #"First");
self.tabBarItem.image = [UIImage imageNamed:#"first"];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
FirstViewController *sharedManager = [FirstViewController sharedManager];
NSLog(#"Toll%#",sharedManager);
// Do any additional setup after loading the view, typically from a nib.
//Get JSON and load into 'data'
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:GWDiOSURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
//Begin JSON Data Parsing and loading
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
//Parse JSON
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
// Load JSON into a dictionary
NSDictionary *tabData = [json objectForKey:#"mapper"];
// Get Tab3 data from dictionary
NSDictionary *tab3 = [tabData objectForKey:#"#tab3_content"];
// Load Tab3 data into a string from dictionary
NSString *html = [NSString stringWithFormat:#"%#",tab3];
// Verify content via counsel
//NSLog(#"Second Data:%#",html);
// Load content into webView
[webView loadHTMLString:html baseURL:nil];
[FirstViewController sharedManager].someProperty = #"asdf";
}
+ (id)sharedManager {
static FirstViewController *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}
I need to set the value of html to the singleton. The follow line
[FirstViewController sharedManager].someProperty = #"asdf";
produces this error
Propery 'someProperty' not found on object of type 'id'.
I have been trying to get this whole process to work for days.. I appreciate the insight.
Well, your class method, sharedManager, returns an id. Try returning FirstViewController* in sharedManager.
+ (FirstViewController *)sharedManager;

NSManagedObjectContext: From a UIViewController, how do you get the ManagedObjectContext in iOS?

How do you know what the proper ManagedObjectContext is? Because I'm not in the appDelegate (where I think the code is) and I keep getting crashes in my app - specifically, in the 'ViewDidLoad' for MyTabBarViewController and the 'sendPressed' method for SecondViewController.
Could you tell me how to find the context? Because alloc init'ing my own context didn't work. Am I suppose to send a message to the appDelegate? I thought adding the appDelegate header file or calling it was the wrong thing to do.
SecondViewController.m
#import "SecondViewController.h"
#implementation SecondViewController
- (IBAction) sendPressed:(UIButton *)sender
{
for(UIViewController *controller in self.tabBarController.viewControllers)
{
if([controller isKindOfClass:[FirstViewController class]])
{
FirstViewController *fvc = (FirstViewController *)controller;
[fvc realLabel];
}
}
//add image to Core Data
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
Photo *photo = [NSEntityDescription insertNewObjectForEntityForName:#"Photo" inManagedObjectContext:context];
photo.photo = imageData;
self.tabBarController.selectedIndex = 2;//switch over to the third view to see if it worked
}
...
#end
MyTabBarViewController.m
#import "MyTabBarViewController.h"
#implementation MyTabBarViewController
#synthesize pageControl,scroller;
-(IBAction)clickPageControl:(id)sender
{
int page=pageControl.currentPage;
CGRect frame=scroller.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
[scroller scrollRectToVisible:frame animated:YES];
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
int page = scrollView.contentOffset.x/scrollView.frame.size.width;
pageControl.currentPage=page;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
scroller.delegate=self;
scroller.pagingEnabled=YES;
scroller.directionalLockEnabled=YES;
scroller.showsHorizontalScrollIndicator=NO;
scroller.showsVerticalScrollIndicator=NO;
scroller.contentSize=CGSizeMake(pageControl.numberOfPages*scroller.frame.size.width, scroller.frame.size.height);
CGFloat scrollWidth = 0;
int pageNumber = 0;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
request.entity = [NSEntityDescription entityForName:#"Photo" inManagedObjectContext:context];
NSError *error = nil;
NSArray *fetchCount = [context executeFetchRequest:request error:&error];
int pageCount = [fetchCount count];
for (int i=0; i<pageCount; i++)
{
PhotoViewController *pvc = [[PhotoViewController alloc] initWithNibName:#"PhotoViewController" bundle:nil];
CGRect rect = scroller.frame;
rect.size.height = scroller.frame.size.height;
rect.size.width = scroller.frame.size.width;
rect.origin.x = scroller.frame.origin.x + scrollWidth;
rect.origin.y = scroller.frame.origin.y;
pvc.view.frame = rect;
[pvc view];
pvc.label.text = [NSString stringWithFormat:#"%d", pageNumber];
pvc.label.textColor = [UIColor redColor];
Photo *photo = [[Photo alloc] init];
photo = [fetchCount objectAtIndex:i];
UIImage *fetchedImage = [UIImage imageWithData:photo.photo];
pvc.imageView.image = fetchedImage;
[scroller addSubview:pvc.view];
[pvc release];
pageNumber++;
scrollWidth += scroller.frame.size.width;
}
pageControl.numberOfPages=pageCount;
pageControl.currentPage=0;
[self.view addSubview:scroller];
}
...
#end
If I import my CoreDataProjAppDelegate to each of these files and use NSManagedObjectContext *context = [(CoreDataProjAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; then it works fine. But is this the correct way?
You have to set the PersistentStoreCoordinator in order for the context to be valid:
NSPersistentStoreCoordinator *psc = ((CoreDataProjAppDelegate *)[UIApplication sharedApplication].delegate).persistentStoreCoordinator;
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:psc];
This is assuming you have a property on the app delegate named persistentStoreCoordinator which the default core data project will have. The psc is basically the link between your context (scratch pad) and your actual persistent storage (physical database).
Did you create your project with the "Use Core Data" box ticked? If you did that you'll have a managedObjectContext automatically, which you then pass to whatever other classes need it.

Resources