Objective C: button only works if clicked twice - objective-c

My button only registers when it is clicked twice for some reason. Anyone know why?
- (IBAction)refreshButton:(UIButton *)sender {
keynames = [[NSMutableArray alloc] init];
keynums = [[NSMutableArray alloc] init];
Firebase *resp = [[Firebase alloc] initWithUrl: #"https://somelink"];
[resp observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot) {
int x = 0;
[tabView beginUpdates];
for (NSString* key in snapshot.value){
[mutkeynames addObject:key];
[mutkeynums addObject:snapshot.value[key][#"value"]];
x++;
}
[tabView endUpdates];
}];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tabView reloadData];
});
}

Related

Remove all controls (subviews) in UITabBarViewController

I'm fairly new to ios programming and I encountered an issue lately. I'm trying to navigate to a selected tab of a tabbarviewcontroller programmatically. Upon entering that selected tab, remove all controls in it and repopulate it with different controls.
I managed to navigate to that selected tab programmatically, however, i'm unable to remove all the subviews.
Below are snippet of my codes..
- (IBAction)btnSave:(id)sender {
orthoPaedicInjuryTabBarViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"OrthoInjuryTabBarVC"];
orthoPaedicInjuryTabBarViewController.selectedIndex = 2;
[self presentViewController:orthoPaedicInjuryTabBarViewController animated:YES completion:nil];
self.alert = [[UIAlertView alloc] initWithTitle:#"Empty Field, Step3"
message: #"Please fill up the frequency of exercises"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[self.alert show];
}
- (void)viewWillAppear:(BOOL)animated {
Store *MyStore = [Store SharedStore];
OrthoInjury *orthoInjury = MyStore.orthoInjury;
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"dd-MM-yyyy"];
NSString *Dob = [format stringFromDate:orthoInjury.dateOfInjury];
self.lblDateOfInjury.text= Dob;
// Do any additional setup after loading the view, typically from a nib.
self.typeOfExercisesList = [Utility GetTypesOfExercisesList];
self.pickerViewTypesOfexercises.dataSource = self;
self.pickerViewTypesOfexercises.delegate = self;
TherapyPhases *therapyPhases = MyStore.therapyPhases;
self.tbxNumberOfWeeks.text = #(therapyPhases.durationWeeks).stringValue;
if([[orthoInjury.natureOfInjury uppercaseString] isEqualToString:[#"Repetitive Strain Injury" uppercaseString]])
{
NSArray *subArray = [self.view subviews];
if([subArray count] != 0) {
for(int i = 1 ; i < [subArray count] ; i++) {
[[subArray objectAtIndex:i] removeFromSuperview];
/*if ([[subArray objectAtIndex:i] isKindOfClass:[UILabel class]])
{
NSLog(#"%#",[[subArray objectAtIndex:i] text]);
}*/
}
}
}
}
Try below for removing the subviews:-
NSMutableArray *subVws=[self.tabBarController.view.subviews mutableCopy];
[subVws performSelector:#selector(removeFromSuperview)];

Implementing Spotlight feature using NSMetaDataQuery and NStableView Data Source Method

I have implemented spotlight feature in my project using NSMetadataQuery. On receiving NSMetadataQueryDidFinishGatheringNotification Notification I am calling reloadData method of tableView method after formatting the NSMetadataItem of NSMetadataQuery. I am facing below two issues.
[query startQuery] is taking too much time when there is huge data in mac.
Not getting NSMetadataQueryDidUpdateNotification;
Search is fast when I ma using NSArrayController instead of NStableViewDataSource and binding it with query.results. As I need to format the NSMetadataItem so i can't use it.
Can anyone answer how to receive batch notification for better performance of NSMetaDataQuery. or any other way to improve the performance of [query startQuery]
Below is code which I have implemented.
- (void)initiateSearch:(NSString *)seString
{
self.metadataSearch=[[[NSMetadataQuery alloc] init] autorelease];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(queryDidUpdatesfsdf:)
name:NSMetadataQueryDidUpdateNotification
object:metadataSearch];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(initalGatherComplete:)
name:NSMetadataQueryDidFinishGatheringNotification
object:metadataSearch];
NSArray *terms = [seString componentsSeparatedByString:#","];
NSMutableArray *pridicateArray = [NSMutableArray array];
NSPredicate *searchPredicate;
for(NSString *term in terms) {
if([term length] == 0)
{
continue;
}
NSString *trimmedString = [[NSString alloc] initWithFormat:#"*%#*",[term stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
NSPredicate *p = [NSPredicate predicateWithFormat:#"(kMDItemFSName like[cd] %#)",trimmedString];
[pridicateArray addObject:p];
[trimmedString release];
}
if ([pridicateArray count] == 1) {
searchPredicate= [pridicateArray objectAtIndex:0];
}
else
{
searchPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:pridicateArray];
}
[metadataSearch setPredicate:searchPredicate];
NSArray *searchScopes;
searchScopes=[NSArray arrayWithObjects:NSMetadataQueryUserHomeScope,nil];
[metadataSearch setSearchScopes:searchScopes];
NSSortDescriptor *sortKeys=[[[NSSortDescriptor alloc] initWithKey:(id)kMDItemDisplayName
ascending:YES] autorelease] ;
[metadataSearch setSortDescriptors:[NSArray arrayWithObject:sortKeys]];
[metadataSearch setNotificationBatchingInterval:5.0];
[metadataSearch startQuery];
}
- (void)queryDidUpdatesfsdf:sender;
{
NSLog(#"A data batch has been received");
}
- (void)initalGatherComplete:sender;
{
[metadataSearch stopQuery];
p_Thread = [[NSThread alloc] initWithTarget:self selector:#selector(dosome:) object:metadataSearch];
[p_Thread start];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSMetadataQueryDidUpdateNotification
object:metadataSearch];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSMetadataQueryDidFinishGatheringNotification
object:metadataSearch];
}
-(void)dosome: (NSMetadataQuery *)metadataresult
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM/dd/yyyy HH:mm:ss"];
fileListArray = [[NSMutableArray alloc] init];
[fileListArray removeAllObjects];
NSUInteger i=0;
for (i=0; (i < [metadataresult resultCount] && ![p_Thread isCancelled]); i++) {
NSMetadataItem *theResult = [metadataresult resultAtIndex:i];
NSString *displayName = [theResult valueForAttribute:(NSString *)kMDItemFSName];
NSString *displayPath = [theResult valueForAttribute:(NSString *)kMDItemPath];
NSString *fileSize = [theResult valueForAttribute:(NSString *)kMDItemFSSize];
FileList *fileList = [[FileList alloc] init];
[fileList setName:displayName];
[fileList setIsChecked:NO];
[fileList setPath:displayPath];
[fileList setLastModified:[dateFormatter stringFromDate:[theResult valueForAttribute:(NSString *)kMDItemContentModificationDate]]];
[fileList setFileSize:[IBUtility formatedFileSizeForOutlineView:fileSize]];
[fileList setMSize:[fileSize longLongValue]];
[[self fileListArray] addObject:fileList];
if (i%50 == 0 && ![p_Thread isCancelled]) {
[searhFinderTableView performSelectorOnMainThread:#selector(reloadData) withObject:Nil waitUntilDone:YES];
}
}
self.metadataSearch=nil;
if ([[self fileListArray] count] == 0) {
[mSearchingLabel setStringValue:#"Items not found"];
NSRect textFieldFrame = [mSearchingLabel frame];
[mSearchingLabel setFrame:NSMakeRect(mContinuousProgress.frame.origin.x,textFieldFrame.origin.y, textFieldFrame.size.width,textFieldFrame.size.height)];
}
else if(![p_Thread isCancelled])
{
[searhFinderTableView performSelectorOnMainThread:#selector(reloadData) withObject:Nil waitUntilDone:YES];
[mSearchingLabel setHidden:YES];
}
[mContinuousProgress stopAnimation:self];
[dateFormatter release];
[pool release];
}
- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
{
return [fileListArray count];
}
- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
FileList *fileList = [fileListArray objectAtIndex:rowIndex];
if ([[aTableColumn identifier] isEqualToString:#"filePath"])
{
return [fileList valueForKey:#"path"];
}
else if([[aTableColumn identifier] isEqualToString:#"isSelected"])
{
return [NSNumber numberWithBool:fileList.isChecked];
}
else if([[aTableColumn identifier] isEqualToString:#"fileSize"])
{
return [fileList valueForKey:#"fileSize"];
}
else if([[aTableColumn identifier] isEqualToString:#"lastModified"])
{
return [fileList valueForKey:#"lastModified"];
}
return nil;
}

CoreData - could not locate an NSManagedObjectModel

I'm getting the error below, I don't know what I'm doing wrong.
I guess there is the managedobject which cannot be located, but... arf !
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'Boxes''
here is my .m ( only the two main functions )
- (void)loadCoreData
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"Test" object:self];
context = [app managedObjectContext];
NSError *err;
// GET THE JSON
NSString *urlString = [NSString stringWithFormat:#"http://localhost:8888/json.txt"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
NSMutableArray *json = (NSMutableArray* )[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
// FILL THE ENTITY
for (int i = 0; i != 7; i++)
{
Boxes *boxes = [NSEntityDescription insertNewObjectForEntityForName:#"Boxes" inManagedObjectContext:context];
boxes.name = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"name"] ;
boxes.sexe = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"sexe"] ;
boxes.topic = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"topic"] ;
boxes.number = [NSNumber numberWithInt:[[[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"number"] intValue]];
}
request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Boxes" inManagedObjectContext:context];
[request setEntity:entity];
arrayForPredicate = [context executeFetchRequest:request error:&err];
}
- (void) fillSexArray:(NSString *)sexe
{
// PREDICATE TO GET AN ARRAY OF PRODUCT WITH SEXE EQUAL TO
NSPredicate *sex;
if ([sexe isEqualToString:#"both"])
{
sex = [NSPredicate predicateWithFormat:#"sexe = %# OR sexe = %#", #"female", #"male"];
}
else
{
sex = [NSPredicate predicateWithFormat:#"sexe = %#", sexe];
}
NSArray *BoxWithSex = [arrayForPredicate filteredArrayUsingPredicate:sex];
NSMutableArray *mutableArray = [self createMutableArray:BoxWithSex];
// NSLog(#"%#", [[mutableArray objectAtIndex:1] valueForKey:#"name"]);
// NSUInteger numObjects = [mutableArray count];
}
my .h :
#interface AddViewController : UIViewController
{
IBOutlet UIButton *male;
IBOutlet UIButton *female;
IBOutlet UIButton *couple;
UIButton *maleBtn;
BOOL flag;
NSArray *arrayForPredicate;
NSFetchedResultsController *fetchedResultsController;
NSManagedObjectContext *context;
NSFetchRequest *request;
}
#property (nonatomic, retain) WonderAppDelegate *app;
- (void) fillSexArray:(NSString *)sexe;
- (NSMutableArray *)createMutableArray:(NSArray *)array;
- (void)loadCoreData;
- (void)sexeButtonPressed;
- (void)sexeArray;
#end
EDIT creating the managedObject :
+ (id)boxWithDictionary:(NSDictionary *)dict withManagedObjectContext:(NSManagedObjectContext *)managedObjectContext;
{
Boxes *boxes = [NSEntityDescription insertNewObjectForEntityForName:#"Boxes"
inManagedObjectContext:managedObjectContext];
boxes.name = [dict objectForKey:#"name"];
boxes.sexe = [dict objectForKey:#"sexe"];
boxes.topic = [dict objectForKey:#"topic"];
boxes.number = [dict objectForKey:#"number"];
return boxes;
}
This is my .m and it is working like that but i don't want the code of the function Add there i want it on loadCoreData.
//
// AddViewController.m
// CoreDataTuto
//
// Created by Clement Yerochewski on 30/04/12.
// Copyright (c) 2012 Weblib. All rights reserved.
//
#import "AddViewController.h"
#import "Boxes.h"
#implementation AddViewController
#synthesize app, context;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 768, 44)];
UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:#"Add Detail"];
[navBar pushNavigationItem:navItem animated:NO];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:#"Cancel" style:UIBarButtonItemStylePlain target:self action:#selector(cancel)];
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:#"Add" style:UIBarButtonItemStyleBordered target:self action:#selector(add)];
navItem.leftBarButtonItem = cancelButton;
navItem.rightBarButtonItem = addButton;
[self.view addSubview:navBar];
app = [[UIApplication sharedApplication] delegate];
}
return self;
}
- (void) add{
[self dismissModalViewControllerAnimated:YES];
// PREDICATE TO GET AN ARRAY OF PRODUCT WITH A LENGTH NAME <= 5
// NSPredicate *length;
// length = [NSPredicate predicateWithFormat:#"name.length <= 5"];
// NSArray *BoxWithCheapPrice = [array filteredArrayUsingPredicate:length];
// NSLog(#"Box %#", BoxWithCheapPrice);
// PREDICATE TO GET AN ARRAY OF PRODUCT WITH PRICE BETWEEN $MIN AND $MAX
// NSNumber *min = [NSNumber numberWithInteger:30];
// NSNumber *max = [NSNumber numberWithInteger:100];
// NSPredicate *between;
// between = [NSPredicate predicateWithFormat:#"number BETWEEN %#", [NSArray arrayWithObjects:min, max, nil]];
// NSArray *BoxWithPriceBetween = [array filteredArrayUsingPredicate:between];
// NSLog(#"Box %#", BoxWithPriceBetween);
// NSLog(#"%#", [BoxWithPriceBetween valueForKey:#"name"]);
}
- (NSMutableArray *)createMutableArray:(NSArray *)array
{
return [NSMutableArray arrayWithArray:array];
}
- (IBAction) sexeChoosen: (id) sender
{
switch ( ((UIButton*)sender).tag ){
case 0:
[self fillSexArray:#"male"];
break;
case 1:
[self fillSexArray:#"female"];
break;
default:
[self fillSexArray:#"both"];
}
[self sexeButtonPressed];
}
- (void)sexeButtonPressed
{
if (flag)
{
UIImage * maleImg2 = [UIImage imageNamed:#"pressed.png"];
[maleBtn setImage:maleImg2 forState:UIControlStateNormal];
flag = NO;
[self sexeArray];
}
else
{
UIImage * maleImg1 = [UIImage imageNamed:#"unpressed.png"];
[maleBtn setImage:maleImg1 forState:UIControlStateNormal];
flag = YES;
[self sexeArray];
}
}
- (void)sexeArray
{
}
- (void)loadCoreData
{
}
- (void) fillSexArray:(NSString *)sexe
{
context = [app managedObjectContext];
// GET THE JSON
NSString *urlString = [NSString stringWithFormat:#"http://localhost:8888/json.txt"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
NSError *err;
NSMutableArray *json = (NSMutableArray* )[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
// FILL THE ENTITY
for (int i = 0; i != 7; i++)
{
Boxes *boxes = [NSEntityDescription insertNewObjectForEntityForName:#"Boxes" inManagedObjectContext:context];
boxes.name = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"name"] ;
boxes.sexe = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"sexe"] ;
boxes.topic = [[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"topic"] ;
boxes.number = [NSNumber numberWithInt:[[[[json valueForKey:#"boxesDetail"] objectAtIndex:i] valueForKey:#"number"] intValue]];
}
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Boxes" inManagedObjectContext:context];
[request setEntity:entity];
arrayForPredicate = [context executeFetchRequest:request error:&err];
NSPredicate *sex;
// PREDICATE TO GET AN ARRAY OF PRODUCT WITH SEXE EQUAL TO
if ([sexe isEqualToString:#"both"])
{
sex = [NSPredicate predicateWithFormat:#"sexe = %# OR sexe = %#", #"female", #"male"];
}
else
{
sex = [NSPredicate predicateWithFormat:#"sexe = %#", sexe];
}
NSArray *BoxWithSex = [arrayForPredicate filteredArrayUsingPredicate:sex];
NSMutableArray *mutableArray = [self createMutableArray:BoxWithSex];
NSLog(#"SEXE CHOOSEN %#", mutableArray);
// NSLog(#"%#", [[mutableArray objectAtIndex:1] valueForKey:#"name"]);
NSUInteger numObjects = [mutableArray count];
NSLog(#"%d", numObjects);
}
- (void) cancel{
[self dismissModalViewControllerAnimated:YES];
}
- (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
{
flag = YES;
maleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
maleBtn.frame = CGRectMake(40, 47, 107, 75);
[maleBtn setTitle:#"male" forState:UIControlStateNormal];
UIImage * maleImg1 = [UIImage imageNamed:#"unpressed.png"];
[maleBtn setImage:maleImg1 forState:UIControlStateNormal];
[maleBtn addTarget:self action:#selector(sexeChoosen:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:maleBtn];
[self loadCoreData];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Have you updated your model after creating the persistent store? Try to delete your app from the simulator (or the database file) and run it again..

iOS: Image Will Not Delete From Array

I'm working on an app that behaves like a photo gallery, and I'm implementing the option to have the user delete photos from their gallery. To accomplish this, I decided to place an invisible button over each picture. When the user hits an "Edit" button, the hidden delete buttons over each picture become active. I'm using the same IBOutlet over each of the hidden buttons for simplicity, and I've tagged each button appropriately in Interface Builder. When the user taps the button over the picture, an alert view appears asking if they really want to delete it. If they click yes, I call removeObjectAtIndex. Here is the code I'm using:
- (IBAction)deleteButtonPressed:(id)sender {
NSLog(#"Sender is %#", sender);
UIAlertView *deleteAlertView = [[UIAlertView alloc] initWithTitle:#"Delete"
message:#"Are you sure you want to delete this photo?"
delegate:self
cancelButtonTitle:#"No"
otherButtonTitles:#"Yes", nil];
[deleteAlertView show];
int imageIndex = ((UIButton *)sender).tag;
deleteAlertView.tag = imageIndex;
}
- (void)alertView: (UIAlertView *) alertView
clickedButtonAtIndex: (NSInteger) buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex]) {
NSLog(#"User Clicked Yes.");
[self.array removeObjectAtIndex: alertView.tag];
}
[self.user setObject:array forKey:#"images"];
}
The issue here is that when I click "Yes" in the alert view, nothing happens. However, if I tap on the image and click "Yes" a second time, the app crashes, and the debug states:
Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray removeObjectAtIndex:]: index (0) beyond bounds (0)' So, I'm not sure where to go from here, I'm still very new to programming and everything looks correct to me. Any help is much appreciated, thanks!
Here is how I add them into the array:
////start of saving////
- (void)viewWillAppear:(BOOL)animated
{
self.user = [NSUserDefaults standardUserDefaults];
self.array = [[self.user objectForKey:#"images"]mutableCopy];
while(self.array == nil)
{
[self.user setObject:[NSMutableArray arrayWithObject:#""] forKey:#"images"];
self.array = [[self.user objectForKey:#"images"]mutableCopy];
NSLog(#"%#",#"attempting to create an array to store the images in");
}
}
- (void)applicationDidEnterBackground:(UIApplication*)application {
NSLog(#"Image on didenterbackground: %#", imageView);
self.array = [NSMutableArray arrayWithObject:[NSData dataWithData:UIImagePNGRepresentation(imageView.image)]];
[self.array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView2.image)]];
[self.array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView3.image)]];
[self.array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView4.image)]];
[self.array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView5.image)]];
[self.user setObject:self.array forKey:#"images"];
[user synchronize];
}
- (void)viewDidLoad
{
self.user = [NSUserDefaults standardUserDefaults];
NSLog(#"It is %#", self.user);
self.array = [[self.user objectForKey:#"images"]mutableCopy];
imageView.image = [[UIImage alloc] initWithData:[self.array objectAtIndex:0]];
imageView2.image = [[UIImage alloc] initWithData:[self.array objectAtIndex:1]];
imageView3.image = [[UIImage alloc] initWithData:[self.array objectAtIndex:2]];
imageView4.image = [[UIImage alloc] initWithData:[self.array objectAtIndex:3]];
imageView5.image = [[UIImage alloc] initWithData:[self.array objectAtIndex:4]];
imageView6.image = [[UIImage alloc] initWithData:[self.array objectAtIndex:5]];
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:app];
backToGalleryButton.hidden = YES;
tapToDeleteLabel.hidden = YES;
deleteButton1.hidden = YES;
[super viewDidLoad];
}
- (void)viewDidUnload
{
self.user = nil;
}
////end of saving
///// shows the hidden and invisible "delete" button over each photo.
- (IBAction)editButtonPressed:(id)sender {
grabButton.hidden = YES;
editButton.hidden = YES;
backToGalleryButton.hidden = NO;
tapToDeleteLabel.hidden = NO;
deleteButton1.hidden = NO;
}
- (IBAction)deleteButtonPressed:(id)sender {
NSLog(#"Sender is %#", sender);
UIAlertView *deleteAlertView = [[UIAlertView alloc] initWithTitle:#"Delete"
message:#"Are you sure you want to delete this photo?"
delegate:self
cancelButtonTitle:#"No"
otherButtonTitles:#"Yes", nil];
[deleteAlertView show];
int imageIndex = ((UIButton *)sender).tag;
deleteAlertView.tag = imageIndex;
}
- (void)alertView: (UIAlertView *) alertView
clickedButtonAtIndex: (NSInteger) buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex]) {
NSLog(#"User Clicked Yes.");
NSLog(#"Array: %#, index: %d", self.array, alertView.tag);
[self.array removeObjectAtIndex: alertView.tag];
}
[self.user setObject:array forKey:#"images"];
}
#end
EDIT: This is the code I use to put the objects into the UIImageView from the users camera roll:
- (IBAction)grabImage {
self.imgPicker = [[UIImagePickerController alloc] init];
self.imgPicker.delegate = self;
self.imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
_popover = [[UIPopoverController alloc] initWithContentViewController:imgPicker];
[_popover presentPopoverFromRect:self.imageView.bounds inView:self.imageView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
else {
[self presentModalViewController:imgPicker animated:YES];
}
[self.imgPicker resignFirstResponder];
}
// Sets the image in the UIImageView
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {
if (imageView.image == nil) {
imageView.image = img;
[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;
}
if (imageView2.image == nil) {
imageView2.image = img;
[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;
}
if (imageView3.image == nil) {
imageView3.image = img;
[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;
}
if (imageView4.image == nil) {
imageView4.image = img;
[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;
}
}
When I added NSLog(#"Array: %#, index: %d", self.array, alertView.tag); just before removeAtIndex the console says 2012-04-03 18:39:39.066 AppName[1631:f803] Array: (null), index: 0. Could that be the cause? I'm not sure why it would be, I think the code looks fine.
Removing the image from the array is not the only step you have to take. Your code is correct for removing the image from the array, which is why you get image out of bounds the second time, but you also need to remove the image from the UI so the user can no longer delete an image that is not there.
There are many oddities with this code but I think the problem is that you are not calling super on your viewwillappear and viewdidload functions. I would get rid of your viewWillAppear method as it serves no purpose.

Objective C: Adding Images on different pages

I am new to trying to create a book app adapting the page-based application of the new xcode just using the single view app, because it is quite confusing learning the template.
i found this code and i am trying to replace the HTML content of this work to UIImageView but i failed.
- (void) createContentPages
{
NSMutableArray *pageStrings = [[NSMutableArray alloc] init];
for (int i = 1; i < 11; i++)
{
NSString *contentString = [[NSString alloc]
initWithFormat:#"<html><head></head><body><h1>Chapter %d</h1><p>This is the page %d of content displayed using UIPageViewController in iOS 5.</p></body></html>", i, i];
[pageStrings addObject:contentString];
}
pageContent = [[NSArray alloc] initWithArray:pageStrings];
}
what i am trying to is to display different images per page.
here is what i did. (i know it is so wrong i just tried it)
- (void) createContentPages
{
NSMutableArray *pageStrings = [[NSMutableArray alloc] init];
for (int i = 1; i < 11; i++)
{
NSArray *photos = [[NSArray arrayWithObjects:
[UIImage imageNamed:#"p1.png"],
[UIImage imageNamed:#"p2.png"],
[UIImage imageNamed:#"p3.png"],
[UIImage imageNamed:#"p4.png"],
nil];
[pageStrings addObject:photos];
}
pageContent = [[NSArray alloc] initWithArray:pageStrings];
}
and it has UIWebView in each page. is it possible that if i replace it with UIImageView it will run?
Here's the rest of the code:
- (void)viewDidLoad
{
[super viewDidLoad];
[self createContentPages];
NSDictionary *options =
[NSDictionary dictionaryWithObject:
[NSNumber numberWithInteger:UIPageViewControllerSpineLocationMin]
forKey: UIPageViewControllerOptionSpineLocationKey];
self.pageController = [[UIPageViewController alloc]
initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl
navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
options: options];
pageController.dataSource = self;
[[pageController view] setFrame:[[self view] bounds]];
contentViewController *initialViewController =
[self viewControllerAtIndex:0];
NSArray *viewControllers =
[NSArray arrayWithObject:initialViewController];
[pageController setViewControllers:viewControllers
direction:UIPageViewControllerNavigationDirectionForward
animated:NO
completion:nil];
[self addChildViewController:pageController];
[[self view] addSubview:[pageController view]];
[pageController didMoveToParentViewController:self];
}
- (contentViewController *)viewControllerAtIndex:(NSUInteger)index
{
// Return the data view controller for the given index.
if (([self.pageContent count] == 0) ||
(index >= [self.pageContent count])) {
return nil;
}
// Create a new view controller and pass suitable data.
contentViewController *dataViewController =
[[contentViewController alloc]
initWithNibName:#"contentViewController"
bundle:nil];
dataViewController.dataObject =
[self.pageContent objectAtIndex:index];
return dataViewController;
}
- (NSUInteger)indexOfViewController:(contentViewController *)viewController
{
return [self.pageContent indexOfObject:viewController.dataObject];
}
- (UIViewController *)pageViewController:
(UIPageViewController *)pageViewController viewControllerBeforeViewController:
(UIViewController *)viewController
{
NSUInteger index = [self indexOfViewController:
(contentViewController *)viewController];
if ((index == 0) || (index == NSNotFound)) {
return nil;
}
index--;
return [self viewControllerAtIndex:index];
}
- (UIViewController *)pageViewController:
(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
NSUInteger index = [self indexOfViewController:
(contentViewController *)viewController];
if (index == NSNotFound) {
return nil;
}
index++;
if (index == [self.pageContent count]) {
return nil;
}
return [self viewControllerAtIndex:index];
}
on subclass
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[webView loadHTMLString:dataObject
baseURL:[NSURL URLWithString:#""]];
}
All time you may use the pictures inside HTML page using the HTML tag <IMG>. So, no the reason to use UIImageView.
Use your createContentPages() method with this one small change (UIImage alone don't represent anything you can put on a "view" Instead you need to use a UIImageView which holds UIImages):
- (void) createContentPages
{
NSMutableArray *pageStrings = [[NSMutableArray alloc] init];
for (int i = 1; i < 11; i++)
{
NSArray *photos = [[NSArray arrayWithObjects:
[[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"p1.png"] autorelease],
[[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"p2.png"] autorelease],
[[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"p3.png"] autorelease],
[[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"p4.png"] autorelease],
nil];
[pageStrings addObject:photos];
}
pageContent = [[NSArray alloc] initWithArray:pageStrings];
}
You can use the code from the main controller (the big block of code that you posted).
The only changes you'll need to make are in what you're calling the "subclass." (really it's the UIPageViewController that handles showing the actual pages).
In that UIPageViewController remove the "webView" (UIWebView). This is probably done in the .xib file (doesn't look like it's added in the code). Then make, viewWillAppear in the UIPageViewController look like this:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.view = dataObject;
}
That should do the trick. Basically, we are no longer using the UIWebView to show HTML data, and instead just adding the dataObject (a UIImageView) as a subview of the UIPageViewController. Hope this helps!