guys. I have two view controllers with two uiwebviews.
Here is my code:
First controller:
#import "articleView.h"
#interface articleView (Private)
- (BOOL) string:(NSString *)string containsString:(NSString *) stringToFind;
#end
#implementation articleView
#synthesize item;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (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];
center = loaderView.bounds;
loadingArticleContent = 0;
if ([item objectForKey:#"article"] == nil) {
[LoadingView showLoadingViewAddedTo:loaderView];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
loaderView.alpha = 0.7;
[UIView commitAnimations];
NSString *link = [item objectForKey:#"link"];
currentArticleLoader *loader = [[currentArticleLoader alloc] init];
loader.link = link;
loader.delegate = self;
[loader load];
} else {
if (webView.loading == NO) {
[self loadWebView:(NSString *)[item objectForKey:#"article"]];
}
}
UIBarButtonItem *itemBar = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:#selector(showToolbar)];
self.navigationItem.rightBarButtonItem = itemBar;
[itemBar release];
self.title = (NSString *)[item objectForKey:#"title"];
self.navigationController.toolbar.tintColor = self.navigationController.navigationBar.tintColor;
}
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
favorited = [[[NSUserDefaults standardUserDefaults] objectForKey:#"favorites"] mutableCopy];
if (favorited.count == 0) {
favorited = [[NSMutableArray alloc] init];
[[NSUserDefaults standardUserDefaults] setObject:favorited forKey:#"favorites"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
bought = [[NSUserDefaults standardUserDefaults] boolForKey:#"com.unnamed.habr.full"];
UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:#selector(share)];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"28-star.png"] style:UIBarButtonItemStylePlain target:self action:#selector(addToFavorites)];
UIBarButtonItem *item3 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"71-compass.png"] style:UIBarButtonItemStylePlain target:self action:#selector(openInSafari)];
if (bought == NO) {
item2.enabled = NO;
}
if ([favorited containsObject:item] == NO) {
[self setToolbarItems:[NSArray arrayWithObjects:item1, space, item3, space, item2, nil]];
} else {
[self setToolbarItems:[NSArray arrayWithObjects:item1, space, item3, nil]];
}
[space release];
[item1 release];
[item2 release];
[item3 release];
}
- (void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if ([self.navigationController isToolbarHidden] == NO) {
[self.navigationController setToolbarHidden:YES animated:YES];
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void) updated:(NSString *)string {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
loaderView.bounds = CGRectMake(-90, 110, 110, 110);
loaderView.alpha = 0.5;
[UIView commitAnimations];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:item];
[dict setValue:string forKey:#"article"];
item = [[NSDictionary alloc] initWithDictionary:dict];
[self loadWebView:string];
[dict release];
}
- (void) loadWebView:(NSString *)body {
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
NSString *title = [item objectForKey:#"title"];
NSString *blog = [item objectForKey:#"blog"];
NSString *bloglink = [item objectForKey:#"bloglink"];
NSString *author = [item objectForKey:#"author"];
NSString *html = [[NSString alloc] initWithFormat:#"<html><head></script><link rel=\"stylesheet\" href=\"mobile.css\" type=\"text/css\" media=\"all\" charset=\"utf-8\"/><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"></head><body><h3>%# → %# </h3> </br> %# </br> <div class=\"m\">Автор: %#</div></body></html>", bloglink, blog, title, body, author];
loadingArticleContent = 1;
[webView loadHTMLString:html baseURL:baseURL];
[html release];
}
- (void)addToFavorites {
[favorited addObject:item];
[[NSUserDefaults standardUserDefaults] setObject:favorited forKey:#"favorites"];
[[NSUserDefaults standardUserDefaults] synchronize];
UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"124-bullhorn.png"] style:UIBarButtonItemStylePlain target:self action:#selector(share)];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"71-compass.png"] style:UIBarButtonItemStylePlain target:self action:#selector(openInSafari)];
[self setToolbarItems:[NSArray arrayWithObjects:item1, space, item2, nil]];
[space release];
[item1 release];
[item2 release];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
NSLog(#"Link: %#", [[request mainDocumentURL] absoluteString]);
if (bought == YES && loadingArticleContent == 0) {
if ([self string:[[request mainDocumentURL] absoluteString] containsString:#"m.habrahabr.ru/blog/"] ||[self string:[[request URL] absoluteString] containsString:#"m.habrahabr.ru/company/"]) {
ViewController *controller = [[ViewController alloc] initWithNibName:#"ViewController" bundle:nil];
controller.url = [request mainDocumentURL];
controller.title = [NSString stringWithFormat:#"%#", (NSString *)[item objectForKey:#"blog"]];
[self.navigationController pushViewController:controller animated:YES];
[controller release];
} else {
webViewController *controller = [[webViewController alloc] initWithNibName:#"webViewController" bundle:nil];
controller.url = [request URL];
[self.navigationController pushViewController:controller animated:YES];
[controller release];
}
} else {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"iHabr" message:#"Просмотр ссылок возможен только в полной версии программы, как и многие другие функции. Произвести покупку можно на вкладке \"Избранное\"" delegate:self cancelButtonTitle:#"Понятно :(" otherButtonTitles:nil] autorelease];
[alert show];
}
return NO;
} else if (loadingArticleContent == 1) {
loadingArticleContent = 0;
return YES;
}
return YES;
}
- (BOOL) string:(NSString *)string containsString:(NSString *) stringToFind {
NSRange rng = [string rangeOfString:stringToFind];
return rng.location != NSNotFound;
}
- (void) webViewDidFinishLoad:(UIWebView *)webView {
UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"124-bullhorn.png"] style:UIBarButtonItemStylePlain target:self action:#selector(share)];
UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"28-star.png"] style:UIBarButtonItemStylePlain target:self action:#selector(addToFavorites)];
UIBarButtonItem *item3 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"71-compass.png"] style:UIBarButtonItemStylePlain target:self action:#selector(openInSafari)];
if (bought == NO) {
item2.enabled = NO;
}
if ([favorited containsObject:item] == NO) {
[self setToolbarItems:[NSArray arrayWithObjects:item1, space, item3, space, item2, nil]];
} else {
[self setToolbarItems:[NSArray arrayWithObjects:item1, space, item3, nil]];
}
[space release];
[item1 release];
[item2 release];
[item3 release];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1];
loaderView.alpha = 0;
[UIView commitAnimations];
}
- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"iHabr" message:[NSString stringWithFormat:#"Не удалось загрузить статью. %#", error] delegate:nil cancelButtonTitle:#"Понятно :(" otherButtonTitles: nil] autorelease];
[alert show];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
loaderView.hidden = YES;
[UIView commitAnimations];
}
#end
Second controller:
#import "webViewController.h"
#implementation webViewController
#synthesize url;
- (void)viewDidLoad
{
[super viewDidLoad];
[myWebView loadRequest:[NSURLRequest requestWithURL:url]];
UIBarButtonItem *itemBar;
itemBar = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:#selector(showToolbar)];
self.navigationItem.rightBarButtonItem = itemBar;
[itemBar release];
UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[self setToolbarItems:[NSArray arrayWithObjects:space, item1, space, item2,item3, space, item4, space, nil]];
[space release];
[LoadingView showLoadingViewAddedTo:loadingView];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
loadingView.alpha = 0.7;
[UIView commitAnimations];
}
- (void) webViewDidStartLoad:(UIWebView *)webView {
item1.enabled = NO;
item2.enabled = NO;
item3.enabled = NO;
item4.enabled = NO;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
loadingView.alpha = 0.7;
[UIView commitAnimations];
}
- (void) webViewDidFinishLoad:(UIWebView *)webView {
if (webView.canGoBack) {
item1.enabled = YES;
}
if (webView.canGoForward) {
item4.enabled = YES;
}
item2.enabled = YES;
item3.enabled = YES;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
loadingView.alpha = 0;
[UIView commitAnimations];
}
- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"iHabr" message:[NSString stringWithFormat:#"Не удалось загрузить страницу. %#", [error userInfo]] delegate:nil cancelButtonTitle:#"Понятно :(" otherButtonTitles: nil] autorelease];
[alert show];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
loadingView.alpha = 0;
[UIView commitAnimations];
}
- (void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if ([self.navigationController isToolbarHidden] == NO) {
[self.navigationController setToolbarHidden:YES animated:YES];
}
}
After opening URL in second controller, and going back to first, some scrolling up and down - my app showing error EXC_BAD_ACCESS. I turned on NSZombieEnable and now I see this:
* -[webViewController respondsToSelector:]: message sent to deallocated instance 0xec624b0
in my console.
You have to be sure to set the delegate property of the web view to nil before it goes away. Do this both in your dealloc and viewDidUnload methods, since viewDidUnload is not always called before dealloc. What’s happening is that after your view controller is deallocated, the web view still has a reference to its address, and is trying to send it a message (-respondsToSelector:).
Related
In my efforts to upgrade my application to support IOS7 I found out that ImageGallery don't load the images. in others iOS is ok.
In imageGalleryView:
- (void)initWithPhotos:(NSMutableArray *)photoURLStrings andCaptions:(NSArray *)myCaptions moveToPage:(int)page {
captions = [myCaptions copy];
photoUrls = [photoURLStrings copy];
NSLog(#"array---> %#", photoUrls);
photoLoaded = [[NSMutableArray alloc] init];
for (int i=0; i<[photoURLStrings count]; i++) {
[photoLoaded addObject:[NSNumber numberWithBool:FALSE]];
}
[pageControl setNumberOfPages:[photoUrls count]];
//scrollView= [[UIScrollView alloc] init];
scrollView.backgroundColor = [UIColor blackColor];
scrollView.pagingEnabled = TRUE;
scrollView.autoresizesSubviews = TRUE;
scrollView.contentSize = CGSizeMake(320 * [photoUrls count], scrollView.frame.size.height);
scrollView.contentOffset = CGPointMake(self.scrollView.frame.size.width*page, 0);
if (([captions objectAtIndex:page] == nil) || ([[captions objectAtIndex:page] isEqualToString:#""])) {
[textView setHidden:TRUE];
} else {
[textView setHidden:FALSE];
[textView setText:[captions objectAtIndex:page]];
}
[self showImages:page];}
- (void)showImages:(int)page {
AsyncImageViewController *asyncImageView;
if ((page>=0)&&(page<[photoUrls count])) {
if (![[photoLoaded objectAtIndex:page] boolValue]) {
[photoLoaded replaceObjectAtIndex:page withObject:[NSNumber numberWithBool:TRUE]];
asyncImageView = [[AsyncImageViewController alloc] init];
//NSLog(#"%#",[NSString stringWithFormat:#"%#",[photoUrls objectAtIndex:page]]);
[asyncImageView loadImageFromURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[photoUrls objectAtIndex:page]]] pos:1];
//NSLog(#"page:%i",page);
asyncImageView.frame = CGRectMake(320*page,0,320,scrollView.frame.size.height);
//[scrollView setBackgroundColor:[UIColor colorWithPatternImage:asyncImageView.image]];
[scrollView addSubview:asyncImageView];
[asyncImageView release];
}
}
page = page - 1;
if ((page>=0)&&(page<[photoUrls count])) {
if (![[photoLoaded objectAtIndex:page] boolValue]) {
[photoLoaded replaceObjectAtIndex:page withObject:[NSNumber numberWithBool:TRUE]];
asyncImageView = [[AsyncImageViewController alloc] init];
[asyncImageView loadImageFromURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[photoUrls objectAtIndex:page]]] pos:1];
asyncImageView.frame = CGRectMake(320*page,0,320,scrollView.frame.size.height);
[scrollView addSubview:asyncImageView];
[asyncImageView release];
}
}
page = page + 2;
if ((page>=0)&&(page<[photoUrls count])) {
if (![[photoLoaded objectAtIndex:page] boolValue]) {
[photoLoaded replaceObjectAtIndex:page withObject:[NSNumber numberWithBool:TRUE]];
asyncImageView = [[AsyncImageViewController alloc] init];
[asyncImageView loadImageFromURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[photoUrls objectAtIndex:page]]] pos:1];
asyncImageView.frame = CGRectMake(320*page,0,320,scrollView.frame.size.height);
[scrollView addSubview:asyncImageView];
//[scrollView setBackgroundColor:[UIColor colorWithPatternImage:asyncImageView.image]];
[asyncImageView release];}}}
In the asyncimageview:
- (void)loadImageFromURL:(NSURL*)url pos:(int) posicio {
if (connection!=nil) { [connection release]; }
if (data!=nil) { [data release]; }
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
loading = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
if (posicio == 0) {
loading.center = CGPointMake(75/2,75/2);
}else {
loading.center = CGPointMake(160,210);
}
[loading startAnimating];
[self addSubview:loading];
[loading release];}//the URL connection calls this repeatedly as data arrives- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {
if (data==nil) { data = [[NSMutableData alloc] initWithCapacity:2048]; }
[data appendData:incrementalData];}//the URL connection calls this once all the data has downloaded- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
//so self data now has the complete image
[connection release];
connection=nil;
if ([[self subviews] count]>0) {
//then this must be another image, the old one is still in subviews
[[[self subviews] objectAtIndex:0] removeFromSuperview]; //so remove it (releases it also)
}//make an image view for the image
imageView = [[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]] autorelease];
//make sizing choices based on your needs, experiment with these. maybe not all the calls below are needed.
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight );
//[self setBackgroundColor:[UIColor colorWithPatternImage:imageView]];
[self addSubview:imageView];
imageView.frame = self.bounds;
[imageView setNeedsLayout];
[self setNeedsLayout];
[loading stopAnimating];
[data release]; //don't need this any more, its in the UIImageView now
data=nil;}
//just in case you want to get the image directly, here it is in subviews- (UIImage*) image {
UIImageView* iv = [[self subviews] objectAtIndex:0];
return [iv image];}
I checked all and saw that it is UIView instead of UIImageView. probably Apple changed something. But xCode don't throw any errors.
Any idea how to fix it?
Ive been searching about a multiple image picker, and I stumble to AGImagePickerController, but then, Im coding in iPad, how can I present the picker in a popoverController from a alertView? Is it possible? or should I shift in presenting it via normal UIButton? Please help.
AGImagePickerController *imagePickerController = [[AGImagePickerController alloc] initWithFailureBlock:^(NSError *error) {
NSLog(#"Fail. Error: %#", error);
if (error == nil) {
NSLog(#"User has cancelled.");
[self dismissModalViewControllerAnimated:YES];
} else {
// We need to wait for the view controller to appear first.
double delayInSeconds = 0.015;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self dismissModalViewControllerAnimated:YES];
});
}
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
} andSuccessBlock:^(NSArray *info) {
NSLog(#"Info: %#", info);
[self.selectedPhotos setArray:info];
}
[self dismissModalViewControllerAnimated:YES];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}];
// Show saved photos on top
imagePickerController.shouldShowSavedPhotosOnTop = YES;
imagePickerController.selection = self.selectedPhotos;
// Custom toolbar items
AGIPCToolbarItem *selectAll = [[AGIPCToolbarItem alloc] initWithBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:#"+ Select All" style:UIBarButtonItemStyleBordered target:nil action:nil] andSelectionBlock:^BOOL(NSUInteger index, ALAsset *asset) {
return YES;
}];
AGIPCToolbarItem *flexible = [[AGIPCToolbarItem alloc] initWithBarButtonItem:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] andSelectionBlock:nil];
AGIPCToolbarItem *selectOdd = [[AGIPCToolbarItem alloc] initWithBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:#"+ Select Odd" style:UIBarButtonItemStyleBordered target:nil action:nil] andSelectionBlock:^BOOL(NSUInteger index, ALAsset *asset) {
return !(index % 2);
}];
AGIPCToolbarItem *deselectAll = [[AGIPCToolbarItem alloc] initWithBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:#"- Deselect All" style:UIBarButtonItemStyleBordered target:nil action:nil] andSelectionBlock:^BOOL(NSUInteger index, ALAsset *asset) {
return NO;
}];
imagePickerController.toolbarItemsForSelection = [NSArray arrayWithObjects:selectAll, flexible, selectOdd, flexible, deselectAll, nil];
// imagePickerController.toolbarItemsForSelection = [NSArray array];
imagePickerController.maximumNumberOfPhotos = 100;
[self presentModalViewController:imagePickerController animated:YES];
}
you should use this via Round Rect Button:
self.popoverController =
[[UIPopoverController alloc] initWithContentViewController:imagePickerController];
popoverController.delegate = self;
CGRect popoverRect = [self.view convertRect:[YOURBUTTON frame]
fromView:[YOURBUTTON superview]];
popoverRect.size.width = MIN(popoverRect.size.width, 100);
[self.popoverController
presentPopoverFromRect:popoverRect
inView:self.view
permittedArrowDirections:UIPopoverArrowDirectionAny
animated:YES];
[popoverController setPopoverContentSize:CGSizeMake(1024, 500)];
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.
I know this is a very stupid question to ask but i have a view controller which has a mapview in it and some uibuttons i have done every thng to eliminate all the leaks bt still after 2-3 toggle between two controller app crashs. Below is the code for allocation and dellocation. BTW i dont get any "did recive memoru warning".. Thnx alot
.h/
#interface MapView : BaseViewController <MKMapViewDelegate,MKAnnotation> {
MKMapView *mapView;
NSMutableArray *placeName;
NSString *mid;
UISegmentedControl *segmentedControl;
IBOutlet UILabel *numberofbeeps;
NSInteger badgenumber;
}
#property (nonatomic, retain) UILabel *numberofbeeps;
#property(nonatomic, retain) NSString *mid;
#property (nonatomic, retain) IBOutlet MKMapView *mapView;
#property(nonatomic,retain) NSMutableArray *placeName;
#property (nonatomic,retain) IBOutlet UISegmentedControl *segmentedControl;
-(IBAction)refreshButtonPressed:(id)sender;
-(IBAction) segmentedControlIndexChanged;
-(IBAction)SignUpButtonPressed:(id)sender;
-(IBAction)BackButtonPressed:(id)sender;
-(IBAction)AddBeepButtonPressed:(id)sender;
-(id)initWithAnnotation:(id ) annotation;
-(IBAction)sliderChanged:(id)sender;
-(IBAction)MyAccountPageButtonPressed:(id)sender;
-(IBAction)MyBeepsButtonPressed:(id)sender;
#end
.m/
-(void)network:(WNetwork*)network didFinishLoadingWithRequest:(NSInteger)pReq data:(NSMutableDictionary*)pData
{
[self removeLoader];
switch (pReq) {
case JBJsonParser:
{
NSMutableArray *array = [NSMutableArray new];
self.placeName = array;
[array release];
self.placeName = pData;
badgenumber = [placeName count];
NSString *checkstring = [[AppHelper mDataManager] objectForKey:#"numberofbeepsnearby"];
NSInteger check = [checkstring intValue];
switch (check) {
case 0:
{
self.numberofbeeps.text =[NSString stringWithFormat:#"No beeps found nearby. Why not beep something?"];
NSLog(#"%#",checkstring);
}
break;
case 1:
{
self.numberofbeeps.text =[NSString stringWithFormat:#"%# beep found nearby! %d beeps worldwide.",checkstring,badgenumber];
NSLog(#"%#",checkstring);
}
break;
default:
{
self.numberofbeeps.text =[NSString stringWithFormat:#"%# beeps found nearby! %d beeps worldwide.",checkstring,badgenumber];
NSLog(#"%#",checkstring);
}
break;
}
if ([placeName count])
{
for (int i =0; i < [placeName count]; i++)
{
NSDictionary *dict = [placeName objectAtIndex:i];
CLLocationCoordinate2D coordinatemain;
coordinatemain.latitude = [[dict objectForKey:#"Lat"] doubleValue];
coordinatemain.longitude = [[dict objectForKey:#"long"] doubleValue];
DLog(#"id of Beeps %#", mid);
NSString *username = [NSString stringWithFormat:#"by %#",[dict objectForKey:#"username"]];
MyAnnotation *ann = [[MyAnnotation alloc] init];
ann.title = [dict objectForKey:#"beep"];
ann.subtitle = username;
ann.beepid=[dict objectForKey:#"beepid"];
ann.coordinate = coordinatemain;
ann.coordinate.latitude == [[dict objectForKey:#"Lat"] doubleValue];
ann.coordinate.longitude == [[dict objectForKey:#"long"] doubleValue];
[mapView addAnnotation:ann];
[ann release];
}
}
}
break;
default:
break;
}
}
-(IBAction) segmentedControlIndexChanged{
switch (self.segmentedControl.selectedSegmentIndex) {
case 0:
{
Screen1 *objCont = [[Screen1 alloc] initWithNibName:#"Screen1" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
break;
case 1:
{
MapView *objCont = [[MapView alloc] initWithNibName:#"MapView" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
break;
default:
break;
}
}
#pragma mark -
#pragma mark request delegates
-(void)makeAccomodationRequest
{
NSMutableDictionary *paramDic = [[NSMutableDictionary alloc] init];
[self.mWNetowrk makeRequsetWithURL:URL_Showbeepsmap type:JBJsonParser paramDictionary:paramDic delegate:self];
[paramDic autorelease];
}
-(BOOL)network:(WNetwork*)network shouldStartForRequest:(NSInteger)pReq
{
[self addLoaderWithtext:#"Loading"];
return YES;
}
-(void)network:(WNetwork*)network didFailForRequest:(NSInteger)pReq WithError:(NSString*)error
{
[AppHelper showAlert:error];
[self removeLoader];
}
-(void)initializeView
{
[self initializeOutlets];
[self makeAccomodationRequest];
}
-(void)initializeOutlets
{
}
-(IBAction)BackButtonPressed:(id)sender
{
Screen1 *objCont = [[Screen1 alloc] initWithNibName:#"Screen1" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
-(IBAction)refreshButtonPressed:(id)sender
{
MapView *objCont = [[MapView alloc] initWithNibName:#"MapView" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
-(IBAction)MyAccountPageButtonPressed:(id)sender
{
NSString *sid = [[AppHelper mDataManager] objectForKey:#"logout"];
{
NSDecimalNumber *session = [[AppHelper mDataManager] objectForKey:#"sid"];
if ([sid isEqualToString:#"logged out"]||session==NULL) {
AddPlace *objCont = [[AddPlace alloc] initWithNibName:#"AddPlace" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
else {
MyAccountPage *objCont = [[MyAccountPage alloc] initWithNibName:#"MyAccountPage" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
}
}
-(IBAction)MyBeepsButtonPressed:(id)sender
{
NSString *sid = [[AppHelper mDataManager] objectForKey:#"logout"];
NSDecimalNumber *session = [[AppHelper mDataManager] objectForKey:#"sid"];
//NSString *sessionStr = [session stringValue];
if ([sid isEqualToString:#"logged out"]||session==NULL) {
[[AppHelper mDataManager] setValue:#"MyBeeps" forKey:#"appflow"];
AddPlace *objCont = [[AddPlace alloc] initWithNibName:#"AddPlace" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
else {
MyBeeps1 *objCont = [[MyBeeps1 alloc] initWithNibName:#"MyBeeps1" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
}
-(IBAction)AddBeepButtonPressed:(id)sender
{
NSString *sid = [[AppHelper mDataManager] objectForKey:#"logout"];
NSDecimalNumber *session = [[AppHelper mDataManager] objectForKey:#"sid"];
if([sid isEqualToString:#"logged out"]||session==NULL) {
[[AppHelper mDataManager] setValue:#"Addabeep" forKey:#"appflow"];
AddPlace *objCont = [[AddPlace alloc] initWithNibName:#"AddPlace" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
else {
[[AppHelper mDataManager] setValue:#"Addabeep" forKey:#"appflow"];
Check20M *objCont = [[Check20M alloc] initWithNibName:#"Check20M" bundle:nil];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve ;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
}
#pragma mark -
#pragma mark MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if (annotation == mapView.userLocation) {
// NSLog(#"nil");
return nil; }
MKPinAnnotationView *pinView = nil;
static NSString *defaultPinID = #"com.invasivecode.pin";
pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if ( pinView == nil )
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
pinView.pinColor = MKPinAnnotationColorGreen;
pinView.frame=CGRectMake(0, 0, 30, 30);
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
MyAnnotation *temp = (MyAnnotation*)annotation;
infoButton.tag = [temp.beepid integerValue];
[infoButton addTarget:self action:#selector(showDetails:) forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = infoButton;
[defaultPinID release];
return pinView;
}
-(IBAction)showDetails:(id)sender{
UIButton *button = (UIButton*)sender ;
NSLog(#"Annotation Click");
BeepsDetail *objCont = [[BeepsDetail alloc] initWithNibName:#"BeepsDetail" bundle:nil];
objCont.mId = [NSString stringWithFormat:#"%d",button.tag];
objCont.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController: objCont animated: YES];
[objCont release];
}
#pragma mark -
#pragma mark mapView delegates
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
mapView.delegate = self;
[self initializeView];
mapView.showsUserLocation = YES;
[self makeAccomodationRequest];
CLLocation *location = [[AppHelper appDelegate] mLatestLocation];
MKCoordinateRegion region;
region.center.latitude = location.coordinate.latitude;
region.center.longitude = location.coordinate.longitude;
region.span.latitudeDelta = 0.001;
// Add a little extra space on the sides
region.span.longitudeDelta = 0.001;
// Add a little extra space on the sides
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:YES];
}
// Listen to change in the userLocation
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.mapView = nil;
self.numberofbeeps =nil;
self.mapView = nil;
self.segmentedControl = nil;
}
- (void)dealloc
{
[mapView release];
// [self.mapView removeFromSuperview];
[placeName release];
//[mid autorelease];
[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.
}
#end
The following only works on the simulator not on device...
Here is a good procedure for finding bad access errors using zombies. All the tools are built into Xcode.
First change to profiling. Click and hold one the run button.
Now choose zombies. This tool warns you just before you are about to use a deallocated object which would other wise trigger a bad access.
Now when a zombie is detected you will see something like this (minus annotatios!) using the tools you can see the object lifecycle. Double click to be taken the the code.
Hope it helps someone!
I would suggest declaring modal view controllers (objCont) as autorelease as opposed to manually releasing them.
I was using NSXML parser for parsing but it was not calling the parser delegate methods, its shows zero error but i don't know where i made a mistake. and i need to parse attribute contents also.
Thanks in advance
Here is my xml file and code
**1.
xml file
** <ROOT_ELEMENT><RESPONSE READ_TAG="LEVEL_LIST" RESULT="" TEXT=""/><USER USER_NAME="newadmin01" TOKEN_ID="0.6864221651800831" FULL_NAME="newadmin01, newadmin01"/><DATETIME UNFORMATTED_TEXT="Aug 10 2011 5:23PM" FORMATTED_TEXT="10 Aug 17:23"/><BREADCRUMB/><LEVEL_LIST><LEVEL ID="4519" NAME="Mega Mart" CHILD_EXISTS="Y" ADD_EDIT_PRIVILEGE="Y"/></LEVEL_LIST></ROOT_ELEMENT>
**2.
.h file
**
#interface MainLevelList : UIViewController
<UITableViewDataSource, UITableViewDelegate, UINavigationControllerDelegate, UISearchBarDelegate, NSXMLParserDelegate> {
UITableView *theTableView;
UILabel *lbl_title;
UILabel *lbl_time;
NSMutableArray *mainLevelListArray;
NSXMLParser *parser;
NSMutableString *elemName;
NSMutableString *currentValueString;
}
#property (nonatomic,retain) IBOutlet UILabel *lbl_title;
#property (nonatomic,retain) IBOutlet UILabel *lbl_time;
#property (nonatomic,retain) IBOutlet UITableView *theTableView;
#property (nonatomic, retain) NSMutableArray *mainLevelListArray;
- (IBAction)onClickLeftArrow;
- (IBAction)onClickRightArrow;
#end
**
- **3. .m file
**
#implementation MainLevelList
#synthesize mainLevelListArray;
#synthesize theTableView;
#synthesize lbl_title;
#synthesize lbl_time;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
[button1 setImage:[UIImage imageNamed:#"answerBtn.png"] forState:UIControlStateNormal];
[button1 setFrame:CGRectMake(0, 0, 66, 34)];
[button1 addTarget:self action:#selector(answerBtn:) forControlEvents:UIControlEventTouchUpInside];
[button1 setTitle:#"Answer" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button1];
NSMutableArray *toolBarItems = [[[NSMutableArray alloc] init] autorelease];
[toolBarItems addObject:barButtonItem];
//[self setToolbarItems:toolBarItems];
UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 setImage:[UIImage imageNamed:#"btmbar_Bg.png"] forState:UIControlStateNormal];
[button3 setFrame:CGRectMake(150, 0, 66, 34)];
[button3 addTarget:self action:#selector(home:) forControlEvents:UIControlEventTouchUpInside];
[button3 setTitle:#"Home" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem2 = [[UIBarButtonItem alloc] initWithCustomView:button3];
[toolBarItems addObject:barButtonItem2];
button3.hidden = YES;
//[self setToolbarItems:toolBarItems];
UIButton *button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 setImage:[UIImage imageNamed:#"btmbar_Bg.png"] forState:UIControlStateNormal];
[button4 setFrame:CGRectMake(200, 0, 66, 34)];
[button4 addTarget:self action:#selector(home:) forControlEvents:UIControlEventTouchUpInside];
[button4 setTitle:#"Home" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem3 = [[UIBarButtonItem alloc] initWithCustomView:button4];
[toolBarItems addObject:barButtonItem3];
button4.hidden = YES;
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 setImage:[UIImage imageNamed:#"nextBtn.png"] forState:UIControlStateNormal];
[button2 setFrame:CGRectMake(250, 0, 66, 34)];
[button2 addTarget:self action:#selector(home:) forControlEvents:UIControlEventTouchUpInside];
[button2 setTitle:#"Next" forState:UIControlStateNormal];
UIBarButtonItem *barButtonItem1 = [[UIBarButtonItem alloc] initWithCustomView:button2];
[toolBarItems addObject:barButtonItem1];
[self setToolbarItems:toolBarItems];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSString *responseXml = [[NSString alloc] initWithString:[[NSUserDefaults standardUserDefaults] valueForKey:#"responseXml"]];
//[[NSUserDefaults standardUserDefaults] setObject:responseXml forKey:#"responseXml"];
parser = [[NSXMLParser alloc] initWithData:[responseXml dataUsingEncoding:NSUTF8StringEncoding]];
[responseXml release];
[parser setDelegate:self];
BOOL parseFlag = [parser parse];
if (parseFlag == 1)
if(debug)NSLog(#"parseFlag = YES");
else
if(debug)NSLog(#"parseFlag = NO");
UINavigationBar *bar = [self.navigationController navigationBar];
CGRect labelRect = CGRectMake(255, 12, 60, 18);
UILabel *label = [[UILabel alloc] initWithFrame:labelRect];
[bar addSubview:label];
label.text = #"ALRICK";
label.textAlignment = UITextAlignmentLeft;
label.font = [UIFont boldSystemFontOfSize:14];
label.tag = 10;
[label release];
UIButton *logOutButton = [UIButton buttonWithType:100];
[logOutButton setImage:[UIImage imageNamed:#"exitBtn.png"] forState:UIControlStateNormal];
[logOutButton addTarget:self action:#selector(logoutButtonTouched) forControlEvents:UIControlEventTouchUpInside];
[logOutButton setTitle:#"Logout" forState:UIControlStateNormal];
UIBarButtonItem* logOutItem = [[UIBarButtonItem alloc] initWithCustomView:logOutButton];
self.navigationItem.leftBarButtonItem = logOutItem;
[lbl_title setText:#"Chain"];
[lbl_title setTextColor:[UIColor whiteColor]];
NSString *date = [NSDate date];
//NSString *date = [[NSDate date] initWithFormat:#"EEE, MMM, h:mm"];
NSLog(#"date:%#",date);
[lbl_time setText:[NSString stringWithFormat:#"%#",date]];
[lbl_time setTextColor:[UIColor whiteColor]];
mainLevelListArray = [[NSMutableArray alloc] init];
//[tableData addObject:#"ICA"];
// [tableData addObject:#"Bread"];
// [tableData addObject:#"ISF"];
// [tableData addObject:#"OSF"];
// [tableData addObject:#"BBC"];
// [tableData addObject:#"ACC"];
// [tableData addObject:#"CFF"];
}
-(void)answerBtn:(id)sender {
QuestionnaireListView *m_questionnaireList = [[QuestionnaireListView alloc] initWithNibName:#"QuestionnaireListView" bundle:nil];
[self.navigationController pushViewController:m_questionnaireList animated:YES];
[m_questionnaireList release];
}
- (void)logoutButtonTouched {
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)onClickLeftArrow {
//[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)onClickRightArrow {
//[self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)dealloc {
[super dealloc];
[mainLevelListArray release];
}
#pragma mark - UITableView delegate methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [mainLevelListArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *kCustomCellID = #"MyCellID";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = [mainLevelListArray objectAtIndex:indexPath.row];
UIView *m_view = [[[UIView alloc] init] autorelease];
m_view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"listHighlight_bg.png"]];
cell.selectedBackgroundView = m_view;
return cell;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
NSLog(#"element Name = %#", elementName);
NSLog(#"namespace URI = %#", namespaceURI);
NSLog(#"qualified Name = %#", qName);
NSLog(#"attributeDict = %#", attributeDict);
elemName = [[NSString alloc] initWithString:elementName];
attributeDict = [[NSString alloc] initWithString:[attributeDict objectForKey:#"READ_TAG"]];
//attribute = [attributeDict objectForKey:#"READ_TAG"];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if ([elemName isEqualToString:#"RESPONSE"]) {
if (!currentValueString) {
currentValueString = [[NSMutableString alloc] initWithCapacity:1024];
}
[currentValueString appendString:string];
}
else if ([elemName isEqualToString:#"USER"]) {
if (!currentValueString) {
currentValueString = [[NSMutableString alloc] initWithCapacity:1024];
}
[currentValueString appendString:string];
}
if ([elemName isEqualToString:#"DATETIME"]) {
if (!currentValueString) {
currentValueString = [[NSMutableString alloc] initWithCapacity:1024];
}
[currentValueString appendString:string];
}
else if ([elemName isEqualToString:#"BREADCRUMB"]) {
if (!currentValueString) {
currentValueString = [[NSMutableString alloc] initWithCapacity:1024];
}
[currentValueString appendString:string];
}
else if ([elemName isEqualToString:#"LEVEL"]) {
if (!currentValueString) {
currentValueString = [[NSMutableString alloc] initWithCapacity:1024];
}
[currentValueString appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elemName isEqualToString:#"RESPONSE"]) {
[mainLevelListArray addObject:currentValueString];
[currentValueString release];
currentValueString = nil;
[elemName release];
elemName = nil;
}
else if ([elemName isEqualToString:#"USER"]) {
[mainLevelListArray addObject:currentValueString];
[currentValueString release];
currentValueString = nil;
[elemName release];
elemName = nil;
}
else if ([elemName isEqualToString:#"DATETIME"]) {
[mainLevelListArray addObject:currentValueString];
[currentValueString release];
currentValueString = nil;
[elemName release];
elemName = nil;
}
else if ([elemName isEqualToString:#"BREADCRUMB"]) {
[mainLevelListArray addObject:currentValueString];
[currentValueString release];
currentValueString = nil;
[elemName release];
elemName = nil;
}
else if ([elemName isEqualToString:#"LEVEL"]) {
[mainLevelListArray addObject:currentValueString];
[currentValueString release];
currentValueString = nil;
[elemName release];
elemName = nil;
}
}
#end
**
add few lines in viewDidLoad method as given below
(void)viewDidLoad {
[super viewDidLoad];
//NSMutableString *urlString ; //assign url string
NSString *postLength = [NSString stringWithFormat:#"%d", [urlString length]];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[urlString dataUsingEncoding:NSUTF8StringEncoding]];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//write your rest part of viewDidLoad
}
Please check the encoding scheme in xml which you are getting from server side as a response and check your iPhone client code it's UTF8, UTF16 or something else.