init an array in initWithNibName - iphone

I am trying to set up an array in my UIViewController. The nib gets loaded into my app, sometimes repeatedly. I am adding this to my initWithNibName to init the array
NSMutableArray *temp = [[NSMutableArray alloc] initWithObjects:#"one",#"two",#"three",#"four",#"five",nil];
[self setScoreArray:temp];
[temp release];
scoreArray is a MutableArray with synthesized properties. When I go to access the array in viewDidLoad I get [[self scoreArray] count] as 0. Also, when I load the nib repeatedly I get a bad access error. Any suggestions? Am I missing a step. Thanks. I am synthesizing the property for the array, in my class declaration:
NSMutableArray *_scoreArray;
then
#property (nonatomic, retain) NSMutableArray *scoreArray;
then in my implementation
#synthesize scoreArray =_scoreArray;
and in my dealloc
[_scoreArray release], _scoreArray = nil;
I'm editing this post to show how I'm loading the nibs with my RootViewController
- (void) createNewSlide:(NSInteger)slideIndex {
NSDictionary *slideObj = (NSDictionary *)[[self slidesDataSource] objectAtIndex:slideIndex - 1];
NSString *currentTitle = [slideObj objectForKey:#"title"];
[[self slideTitle] setText:currentTitle];
NSString *currentContent = [slideObj objectForKey:#"contentString"];
NSString *currentContentType = [slideObj objectForKey:#"contentType"];
if ([self currentVC] != nil) {
[[self currentVC] reset];
[self setCurrentVC:nil];
}
if ([currentContentType isEqualToString:#"slide"])
{
[[self containerViewController] loadImage:currentContent];
}
else if ([currentContentType isEqualToString:#"quiz"])
{
NSInteger quizNum = [[slideObj objectForKey:#"quizNum"] integerValue];
NSLog(#"%s%#%d",__FUNCTION__,#"quizNum ",quizNum);
QuizViewController *quizView = [[QuizViewController alloc] initWithNibName:#"QuizViewController" bundle:nil];
[self setCurrentVC:quizView];
[quizView release];
[[self containerViewController] replaceSlideWithViewController:[self currentVC]];
}
else if ([currentContentType isEqualToString:#"PIDView"])
{
PIDViewController *PIDView = [[PIDViewController alloc] initWithNibName:#"PIDView" bundle:nil];
[self setCurrentVC:PIDView];
[PIDView release];
[[self containerViewController] replaceSlideWithViewController:[self currentVC]];
}
else if ([currentContentType isEqualToString:#"LoginView"])
{
LoginViewController *login = [[LoginViewController alloc] initWithNibName:#"LoginView" bundle:nil];
[self setCurrentVC:login];
[login release];
[[self containerViewController] replaceSlideWithViewController:[self currentVC]];
}
else if ([currentContentType isEqualToString:#"VakView"])
{
VakViewController *vakView = [[VakViewController alloc] initWithNibName:#"VakView" bundle:nil];
[self setCurrentVC:vakView];
[vakView release];
[[self containerViewController] replaceSlideWithViewController:[self currentVC]];
}
else if ([currentContentType isEqualToString:#"PlanView"])
{
PlanViewController *planView = [[PlanViewController alloc] initWithNibName:#"PlanView" bundle:nil];
[self setCurrentVC:planView];
[planView release];
[[self containerViewController] replaceSlideWithViewController:[self currentVC]];
}
Thanks for your insights.
PlanView is the one that causes the problem. But it is not when it loads, it's when something else loads after it. I have run the analyzer and it reports no memory leaks.
BTW, currentVC is a synthesized property.

How is your UIViewController being created? If it is being created via another nib, then -initWithNibName:bundle: doesn't get called. Instead, -initWithCoder: and -awakeFromNib are called.

Related

Releasing view from stack, tab bar with nav controller

So I am working on a vital update to an app I have on the appstore. I have an app with a tab bar and a nav controller. When the user selects an item from the list it sends the link it is getting from the xml file sent from my server to a detail view controller that is only a web view. The problem I'm having is when the user goes back to the tableview which is the root view for that tab the detail view isn't being released. When you select the other options in the app, the detail view doesn't change. It's not that my data isn't being released from the uishared application data but its the view isn't releasing. I know that there are many similar items like this on here and i've tried all of them. I will give you some of my code and greatly appreciate other tips and tricks. Im 15 and just getting into development so any info helps. Heres the code i think is necessary for anyone to help.
TableViewController
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
NSString * storyLink = [[stories objectAtIndex: storyIndex] objectForKey: #"link"];
// clean up the link - get rid of spaces, returns, and tabs...
storyLink = [storyLink stringByReplacingOccurrencesOfString:#" " withString:#""];
storyLink = [storyLink stringByReplacingOccurrencesOfString:#"\n" withString:#""];
storyLink = [storyLink stringByReplacingOccurrencesOfString:#" " withString:#""];
videoDetailViewController.title = #"Videos";
ExampleAppDataObject* theDataObject = [self theAppDataObject];
theDataObject.videoData = storyLink;
if (self.videoDetailViewController == nil)
{
VideoDetailViewController *aBookDetail = [[[VideoDetailViewController alloc] initWithNibName:#"VideosDetailView" bundle:[NSBundle mainBundle]] autorelease];
self.videoDetailViewController = aBookDetail;
[aBookDetail release];
aBookDetail = nil;
}
[self.navigationController pushViewController:videoDetailViewController animated:YES];
}
DetailViewController:
#import "VideoDetailViewController.h"
#import "RSSEntry.h"
#import "ExampleAppDataObject.h"
#import "AppDelegateProtocol.h"
#implementation VideoDetailViewController
#synthesize activityIndicator;
#synthesize webView;
#synthesize pasteboard;
- (ExampleAppDataObject*) theAppDataObject;
{
id<AppDelegateProtocol> theDelegate = (id<AppDelegateProtocol>) [UIApplication sharedApplication].delegate;
ExampleAppDataObject* theDataObject;
theDataObject = (ExampleAppDataObject*) theDelegate.theAppDataObject;
return theDataObject;
}
- (void)viewDidLoad
{
ExampleAppDataObject* theDataObject = [self theAppDataObject];
NSString *urladdress = theDataObject.videoData;
NSURL *url = [NSURL URLWithString:urladdress];
NSURLRequest *requestobj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestobj];
pasteboard = [UIPasteboard generalPasteboard];
[super viewDidLoad];
}
- (void)dealloc
{
[webView release];
webView = nil;
[activityIndicator release];
[pasteboard release];
[VideoDetailViewController release];
[urlData release];
urlData = nil;
[super dealloc];
}
#end
I skipped a lot of the code that i didnt feel was necessary. If you want the actual files then email me at evan.stoddard#me.com
Don't release the webview in the detailViewController page, instead, put
[webView loadRequest:requestobj]; in in viewDidAppear(), not viewDidLoad
Also:
One way to make the transition smoother, change:
if (self.videoDetailViewController == nil) {
VideoDetailViewController *aBookDetail = [[[VideoDetailViewController alloc] initWithNibName:#"VideosDetailView" bundle:[NSBundle mainBundle]] autorelease];
self.videoDetailViewController = aBookDetail;
[aBookDetail release];
aBookDetail = nil;
}
[self.navigationController pushViewController:videoDetailViewController animated:YES];
Should be:
VideoDetailViewController *aBookDetail = [[VideoDetailViewController alloc] initWithNibName:#"VideosDetailView" bundle:[NSBundle mainBundle]] ;
[self.navigationController pushViewController:videoDetailViewController animated:YES];
[aBookDetail release];
Thanks to Anna Billstrom, I realized that I also should be using viewDidAppear instead of viewDidLoad. This is because I am passing data to the controller through an external data class when an item is selected from the table view. Therefore, the detail view controller is loading before there is data to load from the external data class. viewDidAppear solves this problem by getting data once the view loads after the cell is selected and there is data in the external class.

Memory-management in iOS Programming

I have a little problem with memory management in my iOS App. I load an XML and set all Values in this XML to Spezific Objects. Now my problem is when i reload the XML every 15 - 20 reloads of this XML my app Crash on Parsing here is a sample of my parser.
EDIT: Here ist the ERROR when NSZombie is Enabled if NSZombie is disabled I didn't get an ERROR message.
-[CFNumber retain]: message sent to deallocated instance
thanks for help.
EDIT:
the beginning of my Code:
- (id)init
{
self = [super init];
if (self) {
TheObjects *theObjects = [[TheObjects alloc] init];
[self parse];
}
return self;
}
- (void) reload{
reload = YES;
TheObjects *theTmpObjects = [[TheObjects alloc] init];
[self parse];
}
- (void)parse{
for (id xmlOBject in xmlObjects){
MyObject *object = [[MyObject alloc] init];
object.number1 = [NSNumber numberWithInt:1];
object.number2 = [NSNumber numberWithInt:2];
object.number3 = [NSNumber numberWithInt:3];
if (reload)
[theTmpObjects.objects addObject:object];
else
[theObjects.objects addObject:object];
[object release];
}
//later in my code
TheObjects *localTheTmpObjects = nil;
if (reload){
localTheTmpObjects = theObjects;
theObjects = theTmpObjects;
}
if ([delegate respondsToSelector:#selector(finished:)]){
[delegate performSelector:#selector(finished:) withObject:theObjects];
}
if(reload)
[localTheTmpObjects release];
}
remove the line [localTheTmpObjects release]
you don't own the object
at the end, call the `[localTheTmpObjects autorelease];`
this is because if you release array, all its objects are released and hence may cause crash, when your array may in use
- (id)init
{
self = [super init];
if (self) {
TheObjects *obbjects = [[TheObjects alloc] init];
theObjects = objects;
[objects releas];
[self parse];
}
return self;
}
- (void) reload{
reload = YES;
TheObjects *obbjects = [[TheObjects alloc] init];
thetmpObjects = objects;
[objects releas]; [self parse];
}
- (void)parse{
for (id xmlOBject in xmlObjects){
MyObject *object = [[MyObject alloc] init];
object.number1 = [NSNumber numberWithInt:1];
object.number2 = [NSNumber numberWithInt:2];
object.number3 = [NSNumber numberWithInt:3];
if (reload)
[theTmpObjects.objects addObject:object];
else
[theObjects.objects addObject:object];
[object release];
}
//later in my code
TheObjects *localTheTmpObjects = nil;
if (reload){
localTheTmpObjects = theObjects;
theObjects = theTmpObjects;
}
if ([delegate respondsToSelector:#selector(finished:)]){
[delegate performSelector:#selector(finished:) withObject:theObjects];
}
}

iCloud and CoreData

I am trying to use iCloud with my iOS app. I have the app working on the individual devices but when I added iCloud nothing happened. I have looked all over the web and have found only one example which I did not understand. My app is iOS 5.0 and use core data to store the pages. Below is my app delegate and my view which I display it in. Sorry for the lack of knowledge when it comes to iPhone dev. Please help.
http://goddess-gate.com/dc2/index.php/post/452
thank you
If anyone know/has a full working project of iCloud+CoreData I belive I can figure it out. Right now I just have code snip it's which I don't even know how they get called... If I have a full project I can step through it, so I can fully understand how it works.
The problem is I don't think anything is being called to update the view with the data and I don't belive it is sending it to the cloud but I don't know what to call...
PageFlipperAppDelegate.h
#import <UIKit/UIKit.h>
#import "PageView.h"
#import "SlideShowViewController.h"
#import "PagesCollectionViewController.h"
#import "UiWindowSubclass.h"
#interface PageFlipperAppDelegate : UIResponder <UIApplicationDelegate>
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (nonatomic, retain, readonly) PagesCollectionViewController *collectionViewController;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
#end
PageFlipperAppDelegate.m
#import "PageFlipperAppDelegate.h"
#implementation PageFlipperAppDelegate
#synthesize window;
#synthesize managedObjectContext, managedObjectModel, persistentStoreCoordinator,collectionViewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
[NSThread sleepForTimeInterval:2.75];
collectionViewController = [[PagesCollectionViewController alloc] initWithManagedObjectContext:[self managedObjectContext]];
[(UINavigationController *)[[self window] rootViewController] pushViewController:collectionViewController animated:NO];
[collectionViewController release];
[[self window] makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
//stopping timer since we're going to background
// [(UiWindowSubclass *)self.window stopTimer];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
}
- (void)applicationDidEnterBackground:(UIApplication *)application { [self saveContext]; }
- (void)applicationWillEnterForeground:(UIApplication *)application
{
}
- (void)applicationWillTerminate:(UIApplication *)application { [self saveContext];
}
- (void)dealloc
{
[window release];
[managedObjectContext release];
[managedObjectModel release];
[persistentStoreCoordinator release];
[super dealloc];
}
- (void)awakeFromNib
{
}
- (void)saveContext
{
NSError *error = nil;
if ([self managedObjectContext])
{
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
#pragma mark - Core Data stack
- (NSManagedObjectContext *)managedObjectContext
{
if (managedObjectContext != nil)
{
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
//if (IOS_VERSION_GREATER_THAN_OR_EQUAL_TO(#"5.0")) {
NSManagedObjectContext* moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[moc performBlockAndWait:^{
[moc setPersistentStoreCoordinator: coordinator];
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(mergeChangesFrom_iCloud:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:coordinator];
}];
managedObjectContext = moc;
}
return managedObjectContext;
}
/**
Returns the managed object model for the application.
If the model doesn't already exist, it is created from the application's model.
*/
- (NSManagedObjectModel *)managedObjectModel
{
if (!managedObjectModel)
{
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"PageFlipper" withExtension:#"momd"];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
}
return managedObjectModel;
}
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (persistentStoreCoordinator != nil)
{
return persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"PageFlipper.sqlite"];
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSPersistentStoreCoordinator* psc = persistentStoreCoordinator;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSFileManager *fileManager = [NSFileManager defaultManager];
// Migrate datamodel
NSDictionary *options = nil;
// this needs to match the entitlements and provisioning profile
NSURL *cloudURL = [fileManager URLForUbiquityContainerIdentifier:#"G88FQ4WK29.com.brandonsdesigngroup.3Doodles"];
NSString* coreDataCloudContent = [[cloudURL path] stringByAppendingPathComponent:#"data"];
if ([coreDataCloudContent length] != 0) {
// iCloud is available
cloudURL = [NSURL fileURLWithPath:coreDataCloudContent];
options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
#"3Doodles.store", NSPersistentStoreUbiquitousContentNameKey,
cloudURL, NSPersistentStoreUbiquitousContentURLKey,
nil];
} else {
// iCloud is not available
options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
nil];
}
NSError *error = nil;
[psc lock];
if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
[psc unlock];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"asynchronously added persistent store!");
[[NSNotificationCenter defaultCenter] postNotificationName:#"RefetchAllDatabaseData" object:self userInfo:nil];
});
});
return persistentStoreCoordinator;
}
- (void)mergeiCloudChanges:(NSNotification*)note forContext:(NSManagedObjectContext*)moc {
[moc mergeChangesFromContextDidSaveNotification:note];
NSNotification* refreshNotification = [NSNotification notificationWithName:#"RefreshAllViews" object:self userInfo:[note userInfo]];
[[NSNotificationCenter defaultCenter] postNotification:refreshNotification];
}
- (void)mergeChangesFrom_iCloud:(NSNotification *)notification {
NSManagedObjectContext* moc = [self managedObjectContext];
// this only works if you used NSMainQueueConcurrencyType
// otherwise use a dispatch_async back to the main thread yourself
[moc performBlock:^{
[self mergeiCloudChanges:notification forContext:moc];
}];
}
#pragma mark - Application's Documents directory
/**
Returns the URL to the application's Documents directory.
*/
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
#end
viewController.h
#import <Foundation/Foundation.h>
#import "CollectionViewController.h"
#import "SlideShowViewController.h"
#import "PagesDataSource.h"
#import "PageView.h"
#import "PageViewController.h"
#import "PrototypeView.h"
#import "QuickStart.h"
#interface PagesCollectionViewController : CollectionViewController<quickStartDismiss,NSFetchedResultsControllerDelegate>
{
PagesDataSource *dataSource;
PageViewController *viewController;
#private NSFetchedResultsController *fetchedResultsController__ ;
#private NSManagedObjectContext *managedObjectContext__;
}
#property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
#property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
- (id)initWithManagedObjectContext:(NSManagedObjectContext *)managedObjectContext;
- (IBAction)add:(id)sender;
-(void)setShadowAndColor;
-(void)playSlideShow;
#property (nonatomic, readwrite, assign) BOOL editMode;
#end
#interface PageView (CollectionViewItem)
- (void)setRepresentedObject:(PVPage *)representedObject;
- (PVPage *)representedObject;
-(void)didHoldItem;
-(void)duplicatePage;
#end
#interface PushController : UIViewController
{}
#end
#interface toolBar : UIToolbar
#end
viewController.m
#import "PagesCollectionViewController.h"
#import "PageFlipperAppDelegate.h"
#implementation toolBar
- (void)drawRect:(CGRect)rect {}
#end
#implementation PagesCollectionViewController
#synthesize editMode;
#synthesize fetchedResultsController=__fetchedResultsController;
#synthesize managedObjectContext=__managedObjectContext;
-(void)viewWillAppear:(BOOL)animated{
if (![[NSUserDefaults standardUserDefaults] integerForKey:#"integerKey"]) {
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:#"integerKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
QuickStart*stickieViewController = [[[QuickStart alloc]init]autorelease];
stickieViewController.delegate = self;
stickieViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:stickieViewController animated:YES];
}
[[self navigationController] setNavigationBarHidden:NO animated:NO];
[[self navigationController] setToolbarHidden:NO animated:NO];
[[[self navigationController] toolbar] setBarStyle:UIBarStyleBlackTranslucent];
[self setToolbarItems:[NSArray arrayWithObjects:
[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease],
[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:#selector(playSlideShow)]autorelease],
[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease],
nil]];
[(CollectionView*)[self view] setCanReloadData:YES];
[(CollectionView*)[self view]layoutSubviews];
}
- (NSFetchedResultsController *)fetchedResultsController
{
if (__fetchedResultsController != nil)
{
return __fetchedResultsController;
}
/*
Set up the fetched results controller.
*/
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Page" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptorName = [[NSSortDescriptor alloc] initWithKey:#"<sort key>" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptorName, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:#"<section name key path>" cacheName:#"<cache name>"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptorName release];
[sortDescriptors release];
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __fetchedResultsController;
}
// because the app delegate now loads the NSPersistentStore into the NSPersistentStoreCoordinator asynchronously
// we will see the NSManagedObjectContext set up before any persistent stores are registered
// we will need to fetch again after the persistent store is loaded
- (void)reloadFetchedResults:(NSNotification*)note {
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
if (note) {
[(CollectionView*)[self view] setCanReloadData:YES];
[(CollectionView*)[self view]layoutSubviews];
}
}
-(void) playSlideShow{
SlideShowViewController *slideShowViewController = [[[SlideShowViewController alloc] init]autorelease];
NSMutableArray *tempArrayOfImages = [[[NSMutableArray alloc] init]autorelease];
for (int i = 0; i < [[dataSource pages]count]; i++) {
if ([[[dataSource pages] objectAtIndex:i] thumbnail] != nil) {
[tempArrayOfImages addObject: [[[dataSource pages] objectAtIndex:i] thumbnail]];
}
}
[[self navigationController] pushViewController:slideShowViewController animated:YES];
[slideShowViewController setImagesInImageViewer:tempArrayOfImages];
}
-(void)dismissQuickStart{
[self dismissModalViewControllerAnimated:YES];
}
- (id)initWithManagedObjectContext:(NSManagedObjectContext *)managedObjectContext
{
if ((self = [super initWithNibName:#"CollectionView" bundle:nil]))
{
if (editMode == NO) {
[self finishEditToolBars];
}
[self setTitle:#"Doodles"];
viewController = [[PageViewController alloc] initWithManagedObjectContext:managedObjectContext];
dataSource = [[PagesDataSource alloc] initWithManagedObjectContext:managedObjectContext];
CGSize itemViewMarginSize = CGSizeMake(25.0, 0.0);
[(CollectionView *)[self view] setItemViewMarginSize:itemViewMarginSize];
PrototypeView *pro = [[[PrototypeView alloc] init] autorelease];
[(CollectionView *)[self view] setItemViewPrototype:pro];
[(CollectionView *)[self view] setFlowDirection:CVFlowDirectionVertical];
[(CollectionView *)[self view] setItemViewFrameSize:CGSizeMake(([(CollectionView *)[self view] bounds].size.width - 3*itemViewMarginSize.width)/3.4, ([(CollectionView *)[self view] bounds].size.height - 3*itemViewMarginSize.height)/3.6)];
[self setShadowAndColor];
}
return self;
}
-(void)setShadowAndColor{
CollectionView *collectionView = (CollectionView *)[self view];
[collectionView setShadowColor:[UIColor blackColor]];
[collectionView setShadowRadius:6.0f];
[collectionView setShadowOpacity:0.5f];
}
- (void)add:(id)sender
{
[dataSource add:sender];
CollectionView *collectionView = (CollectionView *)[self view];
// [collectionView reloadData];
// [collectionView scrollItemIndexToVisible:[self countOfItemsInCollectionView:collectionView]-1 animated:NO];
[collectionView.dataDelegate collectionView:collectionView didSelectItemAtIndex:[self countOfItemsInCollectionView:collectionView]-1];
//CollectionViewController *c;
// [[c transitionToDetailViewController:[c collectionView:self detailViewControllerForItemAtIndex:(NSUInteger)[self countOfItemsInCollectionView:collectionView]-1] forItemView:[itemViews objectForKey:[NSString stringWithFormat:#"%u", [self countOfItemsInCollectionView:collectionView]-1]]]];
// [c transitionToDetailViewController:self forItemView:collectionView.itemViews;
editMode = NO;
//collectionView.canUpdateLayout = YES;
collectionView.canReloadData = YES;
[(CollectionView*)[self view]layoutSubviews];
}
- (NSUInteger)countOfItemsInCollectionView:(CollectionView *)collectionView { return [[dataSource pages] count]; }
- (id)collectionView:(CollectionView *)collectionView representedObjectAtIndex:(NSUInteger)itemIndex {
return [[dataSource pages] objectAtIndex:itemIndex];
}
- (void)collectionView:(CollectionView *)collectionView didSelectItemAtIndex:(NSUInteger)itemIndex
{
if (editMode == YES) {
[collectionView yellowdidSelectItemAtIndex:itemIndex];
// NSLog(#"edit");
}else{
PVPage *selectedPage = [[[dataSource pages] objectAtIndex:itemIndex]autorelease];
PageView *pageView = [[[PageView alloc] init] autorelease];
[pageView setRepresentedPage:selectedPage];
// UIImage *i = [UIImage imageWithData: [[pageView representedPage] thumbnail]];
// UIImageView *ii = [[[UIImageView alloc] initWithImage:i]autorelease];
[viewController setView:pageView];
// [(PageView*)[viewController view] setBackgroundStrokes:ii];
//NSLog(#"selected page %#",selectedPage);
// [[[self navigationController] toolbar] setHidden:YES];
// [[[self navigationController] navigationBar] setHidden:YES];
// [[[self tabBarController] tabBar] setHidden:YES];
PageFlipperAppDelegate *appDelegate = (PageFlipperAppDelegate *)[[UIApplication sharedApplication] delegate];
// [(UiWindowSubclass *)appDelegate.window startTimer];
[(UINavigationController *)[(UiWindowSubclass*)[appDelegate window] rootViewController] pushViewController:viewController animated:YES];
// viewController = nil;
// [[self navigationController] setToolbarHidden:NO];
}
}
- (BOOL)collectionView:(CollectionView *)collectionView canDeleteItemAtIndex:(NSUInteger)itemIndex {
NSLog(#"itemIndex %u",itemIndex);
return YES;
}
- (void)collectionView:(CollectionView *)collectionView didDeleteItemAtIndex:(NSUInteger)itemIndex
{
[dataSource removePageAtIndex:itemIndex];
}
-(void)trash{
// NSLog(#"trash");
[(CollectionView *)[self view] trashitems];
}
-(void)done{
[(CollectionView *)[self view] yellowdidSelectItemAtIndexUndo];
[(CollectionView *)[self view] shakedidRemoveSelectItemAtIndex];
[(CollectionView *)[self view] donereset];
[self finishEditToolBars];
}
-(void) finishEditToolBars{
[[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(add:)] autorelease]];
[[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:#selector(didHoldItem)] autorelease]];
editMode = NO;
}
-(void)duplicatePage{
NSArray *tempArray = [[[(CollectionView*)[self view] selectedItemsArray]copy]autorelease];
// for (int i =0; i<[[(CollectionView*)[self view] selectedItemsArray]count]; i++) {
// [(CollectionView *)[self view] yellowdidSelectItemAtIndex:i];
//
// }
[dataSource duplicatePage:[[[NSArray alloc] initWithArray:tempArray]autorelease]];
CollectionView *collectionView = (CollectionView *)[self view];
editMode = NO;
[self done];
// [(CollectionView *)[self view] yellowdidSelectItemAtIndexUndo];
collectionView.canReloadData = YES;
[collectionView layoutSubviews];
}
-(void)didHoldItem{
[[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(done)] autorelease]];
// [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:#selector(trash)] autorelease]];
toolBar* tools = [[toolBar alloc] initWithFrame:CGRectMake(0, 0, 133, 44.01)];
tools.barStyle = UIBarStyleBlackTranslucent;
tools.opaque = NO;
//tools.backgroundColor = [UIColor clearColor];
// create the array to hold the buttons, which then gets added to the toolbar
NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:3];
// create a standard "add" button
UIBarButtonItem* bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:#selector(trash)];
bi.style = UIBarButtonItemStyleBordered;
[buttons addObject:bi];
[bi release];
// create a spacer
bi = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
[buttons addObject:bi];
[bi release];
// create a standard "refresh" button
bi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:#selector(duplicatePage)];
bi.style = UIBarButtonItemStyleBordered;
[buttons addObject:bi];
[bi release];
// stick the buttons in the toolbar
[tools setItems:buttons animated:NO];
[buttons release];
// and put the toolbar in the nav bar
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:tools] autorelease];
[tools release];
[(CollectionView*)[self view] setOldItemIndex:-1];
editMode = YES;
[(CollectionView*)[self view] setEditMode:YES];
[(CollectionView*)[self view] shakedidSelectItemAtIndex];
}
-(void)didReceiveMemoryWarning{
// NSLog(#"mem");
}
- (void)dealloc
{ [dataSource release],dataSource = nil;
[viewController release],viewController = nil;
[super dealloc];
}
-(void)viewDidAppear:(BOOL)animated{
[ (CollectionView*) [self view] setCanReloadData:YES];
[(CollectionView*) [self view] layoutSubviews];
}
-(void) viewDidLoad{
CollectionView *collectionView = (CollectionView *)[self view];
collectionView.canReloadData = YES;
[(CollectionView*)[self view]layoutSubviews];
editMode = NO;
collectionView.editMode = NO;
}
#end
On the Apple developer forums the iPhoneCoreDataRecipes sample code is posted, which includes iCloud.
https://devforums.apple.com/thread/126670?tstart=0
You can watch this year's WWDC 2012 Session 227 lecture (you can freely access these videos using your Apple Developer account), that will show how to correctly use Core Data and iCloud together, illustrating the correct application architecture, the way Core Data and iCloud should talk to each other and explaining all this stuff through a complete sample project.
Edit
The full source of the project is only available to all registered Apple developers under this page.
This is a very controversial topic... I need to add iCloud with Core Data in my next application but it's a bit hard to start. I have done nothing but I found these documents very useful:
Using Core Data with iCloud Release Notes
Using iCloud in Conjunction with Databases
Your Third iOS App: iCloud
It's not just controversial, it's not working adequately yet. If you are able to code the sample, you'll likely find that it only works on occasion. I wish I could write that it's solved and here is how you use it - maybe someone else can, but as of March 2012, I doubt it.
Still, it's interesting and instructive to code the sample, and the others in the dev site, so that you can learn what iCloud/core data is all about.
A lot of us are chomping at the bit for this to solidify.
You may want to try Dox from Ray Wenderlich's fantastic site. But you'll likely end up with the same frustration. Sometimes it works, mostly not.
Blackpixel have upped a version of Core Data Recipes with iCloud to Github. It may have improvements over the version in the dev forums.
I've used the dev forums version and found that it works, but takes some time to sync. Read the comments thread there (19 pages and counting) and make up your mind about it.

AppDelegate Navigation error

- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSError *error = nil;
NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:#"username"];
NSString *str = [SFHFKeychainUtils getPasswordForUsername:username andServiceName:#"mybibleapp" error:&error];
NSLog(#"previous un");
NSLog(#"%#", str);
if(str != nil)
{
main_page *detailViewController = [[main_page alloc] initWithNibName:#"main_page" bundle:nil];
// Pass the selected object to the new view controller.
// detailViewController.localStringtextnote = localStringtextnote;
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}
When I put this code for navigating to main_page it shows an error that property navigationController not found on object of appdelegate so i put this code insted of the above
main_page *log = [[main_page alloc] initWithNibName:#"main_page" bundle:nil];
[window addSubview:tabController.view];
[window addSubview:log.view];
[window makeKeyAndVisible];
the page is redirected to main_page but nothing is working in this way. no navigation in main_page is working, I cant redirect any page from the main_page. So what can I do to solve these errors.
You can create a "proxy" viewController without nib which is loaded in MainWindow's navigationController and then do something like the following, in the proxy's viewDidLoad
NSError *error = nil;
NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:#"username"];
NSString *str = [SFHFKeychainUtils getPasswordForUsername:username andServiceName:#"mybibleapp" error:&error];
NSLog(#"previous un");
NSLog(#"%#", str);
UIViewController *controller;
if (!error && nil != str) {
controller = [[DetailViewController alloc] init];
} else {
controller = [[LoginViewController alloc] init];
}
[[self navigationController] pushViewController:controller animated:YES];
[controller release];
Initial page loading is usually handled in the MainWindow.xib nib. You shouldn't have to manually load it.
Try creating a new project from a template and then do in and look at how the appDelegate and MainWindow.xib are setup.

Problems with InitWithData

I am trying to InitWithData a viewcontroller with multiple data like this:
NewsDetailViewController *anotherViewController = [[NewsDetailViewController alloc] initWithData:[oldEntries objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:anotherViewController animated:YES];
[anotherViewController release];
[newsTableView deselectRowAtIndexPath:indexPath animated:NO];
So this is the current: InitWithData:initWithData:[oldEntries objectAtIndex:indexPath.row]];
Now I need the InitWithData to push 2 of these objects:
[oldEntries objectAtIndex:indexPath.row];
[reviewEntries objectAtIndex:indexPath.row];
How can I do this?
I receive the current data like this in the NewsDetailController:
- (id)initWithData:(NSDictionary *)data {
if (self == [super init]) {
rssData = [data copy];
}
return self;
}
And rssData is a NSDictionary..
change your init method to
- (id)initWithOldData:(NSDictionary *)oldData
andReviewData:(NSDictionary *)revData {
if (self == [super init]) {
rssOldData = [oldData copy];
rssReviewData = [revData copy];
}
return self;
}
and call it using
[[NewsDetailViewController alloc]
initWithOldData:[oldEntries objectAtIndex:indexPath.row]
andReviewData:[reviewEntries objectAtIndex:indexPath.row]];
Of course you need to declare rssOldDataand rssReviewData in your NewsDetailViewController too.