I seem to be having a problem removing the image in UIScrollView. I was able to remove it from NSDocumentDirectory but it still stays in the view. how to remove it when button is pressed too. Here is my code :
- (IBAction)buttonClicked:(id)sender {
UIButton *button = (UIButton *)sender;
[_images objectAtIndex:button.tag];
[_images removeObjectAtIndex:button.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%d.png", button.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
}
You will need to remove the view from the super view like the following
//In your button clicked function
- (IBAction)buttonClicked:(id)sender {
UIButton *button = (UIButton *)sender;
[button removeFromSuperView];
}
I think after finish your delete option. you doesn't reload your view. so that i remain that image.
Related
As my above screen shot show that I want to show Two values in Each cell of Tableview. I can do it if I have the data which I want to show in these labels of Cell in the same Class,but problem for me is I am try to getting both these labels from other view or other class using (NSDocumentDirectory, NSUserDomainMask, YES) so for I got success to show one value as my screenshot show ,but the other part which consist of current data and time Display is still problem for me.Now here is my code which i try so for.
NSString *fina = [NSString stringWithFormat:#"%#",mySongname];
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
NSString *soundFilePath = [docsDir stringByAppendingPathComponent:#"MyRecordings"];
if (![[NSFileManager defaultManager] fileExistsAtPath:soundFilePath])
[[NSFileManager defaultManager] createDirectoryAtPath:soundFilePath withIntermediateDirectories:NO attributes:nil error:nil];
soundFilePath = [soundFilePath stringByAppendingPathComponent:fina];
recordedTmpFile = [NSURL fileURLWithPath:soundFilePath];
recorder = [[ AVAudioRecorder alloc] initWithURL:recordedTmpFile settings:recordSetting error:&error];
[recorder setDelegate:self];
[recorder prepareToRecord];
[recorder record];
[recordSetting release];
The above part of Code works fine it display the value in Tableview Cell that my screenshow.Now in same function I am try to getting the data to show it in red part which is my UILabel in Tableview Cell using Below Code.
NSDate* now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd:MMM:YY_hh:mm:ss a"];
NSString *file= [dateFormatter stringFromDate:now];
NSLog(#"myfinaldate:%#",file);
Now i want to save this date value in same directory which i use above and to show it red parts of UITableview .
Now here is my Code where i use this Tableview and getting these document directory value.
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentPath = [documentsDirectory stringByAppendingPathComponent:#"MyRecordings"];
directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath:documentPath];
NSLog(#"file found %i",[directoryContent count]);
[directoryContent retain];
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
static NSInteger StateTag = 1;
static NSInteger CapitalTag = 2;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UILabel *capitalLabel = [[UILabel alloc] initWithFrame:CGRectMake(2, 2, 80, 20)];
//capitalLabel.text=#"mydata";
capitalLabel.backgroundColor=[UIColor redColor];
capitalLabel.tag = CapitalTag;
[cell.contentView addSubview:capitalLabel];
[capitalLabel release];
UILabel *stateLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 22, 310, 20)];
stateLabel.tag = StateTag;
[stateLabel setFont:[UIFont systemFontOfSize:14]];
stateLabel.adjustsFontSizeToFitWidth=YES;
[cell.contentView addSubview:stateLabel];
[stateLabel release];
}
UILabel * stateLabel = (UILabel *) [cell.contentView viewWithTag:StateTag];
//UILabel * capitalLabel = (UILabel *) [cell.contentView viewWithTag:CapitalTag];
stateLabel.text = [directoryContent objectAtIndex:indexPath.row];
//capitalLabel.text = [directoryContent1 objectAtIndex:indexPath.row];
return cell;
}
Now I am trying to summarize the problem.
How we can save the date and time value in same directory and then how to show here in Red part of UITableview Cell?
capitalLabel is my Redpart of Cell to show date and time which is problem.
stateLabel all ready show the values. so no problem with this label. Any help will be appreciated.
just do this....
you can set NSCachesDirectory to NSDocumentDirectory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:yourComponent];
// NSLog(#"Path : %#",writableDBPath);
NSMutableDictionary *plistArr = [[NSMutableDictionary alloc] initWithContentsOfFile:writableDBPath];
Having a problem with my code, was able to have a preview with thumbnail with images in a UIScrollView. My images is from NSDocumentDirectory. I can delete from it though but I can delete from it (in terms of VIEW & in NSDocumentDirectory) PROPERLY when I start from the right to left position.
PROBLEM:
Now, I can delete anyway, But I have some several problems.
First, though I can delete, the view is not arranging, my rearrangeItems: method is not being called also.
Second,Then at first load I can delete anyway I like, but like what I said rearrangeItems: method is not being called, so their names
arent renamed.
Third, is at first load, I can delete in anyway, but when I exit the app, I can delete but my images in the NSDocu is not deleting.
Hope anyone could help me with this. Below is the preview of my code.
- (void)addImage:(UIImage *)imageToAdd {
[_images addObject:imageToAdd];
[_thumbs addObject:[imageToAdd imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
int row = floor(([_thumbs count] - 1) / 5);
int column = (([_thumbs count] - 1) - (row * 5));
UIImage *thumb = [_thumbs objectAtIndex:[_thumbs count]-1];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 60);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self action:#selector(deleteItem:) forControlEvents:UIControlEventTouchUpInside];
button.tag = [_images count] - 1;
// This is the title of where they were created, so we can see them move.s
[button setTitle:[NSString stringWithFormat:#"%d, %d", row, column] forState:UIControlStateNormal];
[_buttons addObject:button];
[scrollView addSubview:button];
// This will add 10px padding on the bottom as well as the top and left.
[scrollView setContentSize:CGSizeMake(300, row*60+20+60)];
}
- (void) deleteItem:(id)sender {
_clickedButton = (UIButton *)sender;
UIAlertView *saveMessage = [[UIAlertView alloc] initWithTitle:#""
message:#"DELETE?"
delegate:self
cancelButtonTitle:#"NO"
otherButtonTitles:#"YES", nil];
[saveMessage show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"YES"]) {
NSLog(#"YES was selected.");
UIButton *button = _clickedButton;
[button removeFromSuperview];
[_buttons removeObjectAtIndex:button.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%lu.png", button.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
[self rearrangeItems:button.tag];
}
}
- (void)viewDidAppear:(BOOL)animated
{
[_thumbs removeAllObjects];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
//NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
}
UPDATED: new rearrange method
- (void)rearrangeItems:(int)startIndex {
for (UIButton *button in _buttons) {
// Shift the tags down one
if (button.tag > startIndex) {
NSLog(#"called here");
// Version 2 ****************************
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%lu.png", button.tag]];
NSData *imageData = [NSData dataWithContentsOfFile:fullPath];
[fileManager removeItemAtPath: fullPath error:NULL];
// **************************************
button.tag -= 1;
// Version 2 ****************************
fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%lu.png", button.tag]];
[imageData writeToFile:fullPath atomically:YES];
// **************************************
// Recalculate Position
int row = floor(button.tag / 5);
int column = (button.tag - (row * 5));
// Move
button.frame = CGRectMake(column*61+8, row*61+8, 60, 60);
if (button.tag == [_buttons count] - 1) {
[scrollView setContentSize:CGSizeMake(300, row*61+16+60)];
}
}
}
}
You show "rearrangeButtons" but never use it - I assume the code above is out of date. In any case you have some small issues here:
[_images objectAtIndex:button.tag];
[_images removeObjectAtIndex:button.tag];
[_images removeObject:button];
The first and last statements make no sense, what you should be using is:
[_images removeObjectAtIndex:button.tag];
[self rearrangeButtons:button.tag];
To just add a sanity check to the app, try adding this code to the end of rearrangeButtons:
int idx = 0;
for (UIButton *button in _buttons) {
NSLog(#"Going to query button at index %d", idx);
NSLog(#"Button at index %d is of type %#", idx, NSStringFromClass([button class]);
// if the button is not a UIView subclass, it won't have tag. If its a dealloced
// object then it probably will crash when you ask it its class...
if(button.tag != idx) NSLog(#"INDEX PROBLEM AT BUTTON ARRAY INDEC %d", idx);
++idx;
}
EDIT: code edited in loop to print out the object class
EDIT2: So I took your code and put it into a new project, ButtonManager. Essentially its OK but you have a few problems. First, you index the file names even if no file exists, so the indexes could get out of sync. Second, you use %lu format for a button.tag, but that is an integer so you should be using "%d". Lastly, you delete buttons from the array but not the images or the thumbnails.
If you download that project, you will see warnings in all the places you need to change to get to work properly. I am not sure why the button indexes got corrupted - maybe other code. In any case there is a data consistency test added to the code - sprinkle calls to that around in your code - if its ever fails then you know your problem is between the last good test and the latest failing one.
The project kicks off a "deleteItem:" message when it starts, and just keeps deleting items in the middle of the array as long as you tap YES.
Replace your functions with these
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"YES"]) {
NSLog(#"YES was selected.");
UIButton *button = _clickedButton;
[self rearrangeItems:button.tag];
}
}
- (void)rearrangeItems:(int)startIndex {
for (UIButton *button in _buttons) {
// Shift the tags down one
if (button.tag > startIndex) {
NSLog(#"called here");
[button removeFromSuperview];//remove the button from the scrollview
[_buttons removeObjectAtIndex:button.tag];//remove the button object from _buttons array
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%lu.png", button.tag]];
NSData *imageData = [NSData dataWithContentsOfFile:fullPath];
[fileManager removeItemAtPath: fullPath error:NULL];
button.tag -= 1;
fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%lu.png", button.tag]];
[imageData writeToFile:fullPath atomically:YES];
// Recalculate Position
int row = floor(button.tag / 5);
int column = (button.tag - (row * 5));
// Move
button.frame = CGRectMake(column*61+8, row*61+8, 60, 60);
if (button.tag == [_buttons count] - 1) {
[scrollView setContentSize:CGSizeMake(300, row*61+16+60)];
}
[scrollView setNeedsDisplay];
}
}
Hope this helps.
I'm making my slot machine app using iCarousel, my iCarousel contains images from NSDocumentDirectory this images was from my ImagePicker. So here's how my app works, when the user press a button the iCarousel spins.
When it stops, display the item for 3 seconds, then deletes it.
My problem is when I go to another View, the deleted index/item is there again. How to maintain my array even I go to different views. That the deleted index/item will not be shown, only until the app was restarted, like saving an array. Thanks for the help.
// my array
- (void)viewDidLoad
{
self.images = [NSMutableArray new];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"images%d.png", i]];
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[images addObject:[UIImage imageWithContentsOfFile:savedImagePath]];
}
}
}
- (void)viewWillAppear:(BOOL)animated {
spinButton = [UIButton buttonWithType:UIButtonTypeCustom];
[spinButton addTarget:self action:#selector(spin) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:spinButton];
}
- (void) carouselDidEndScrollingAnimation:(iCarousel *)carousel{
[NSTimer scheduledTimerWithTimeInterval:0.56 //this arranges the duration of the scroll
target:self
selector:#selector(deleteItem)
userInfo:nil
repeats:NO];
}
// spin and delete method
- (void)spin {
[carousel scrollByNumberOfItems:-35 duration:10.7550f];
}
-(void) deleteItem {
//Removes the object chosen
NSInteger index = carousel.currentItemIndex;
[carousel removeItemAtIndex:index animated:YES];
[images removeObjectAtIndex:index];
}
What I need is, when the index/item is deleted, it will not be shown temporarily even if I go to other views. The views will only be restarted after app is closed and open again
Your problem is your are creating the images NSMutableArray every time you enter the view.
As #Saleh said you should place the array outside your view controller. To do it in the appDelegate, like he was suggesting, do the following:
In AppDelegate.h declare:
#property( strong, nonatomic) NSMutableArray *images;
In AppDelegate.m:
#synthesize images;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Read the images after the existing code ....
self.images = [NSMutableArray array];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"images%d.png", i]];
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[images addObject:[UIImage imageWithContentsOfFile:savedImagePath]];
}
}
return YES;
}
Then in your ViewController.m:
#import "AppDelegate.h"
and change your viewDidLoad method:
- (void)viewDidLoad
{
[super viewDidLoad];
self.images = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).images;
}
This should work.
Use one instance of the array, you are initializing it only once. Put the array in appDelegate which will make it singelton for the whole app.
So Im making a two UIscrollview in my view. I'm using Ray Wenderlich's Custom Image Picker. But when I load it, only shows 1 imagepicker. I want to be able to load two image picker. I think Im doing something wrong with initWithCoder part. Cant seem to initialize it properly. Is it possible to have two ivars self. Sorry kinda new to iphoneDev. Thanks for your help.
Here's my whole implementation:
- (id) initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
_images = [[NSMutableArray alloc] init];
_thumbs = [[NSMutableArray alloc] init];
//THIS IS WHERE I THINK ITS WRONG but the upper part seems to be okay.
_images2 = [[NSMutableArray alloc] init];
_thumbs2 = [[NSMutableArray alloc] init];
}
return self;
}
- (void)addImage:(UIImage *)image {
[_images addObject:image];
[_thumbs addObject:[image imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
}
- (void)addImage2:(UIImage *)image {
[_images2 addObject:image];
[_thumbs2 addObject:[image imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
}
- (void) createScrollView {
self.slotBg = [[UIView alloc] initWithFrame:CGRectMake(43, 370, 300, 143)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.slotBg.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor grayColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[self.slotBg.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:self.slotBg];
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,134.0f)];
[slotBg addSubview:scrollView];
int row = 0;
int column = 0;
for(int i = 0; i < _thumbs.count; ++i) {
UIImage *thumb = [_thumbs objectAtIndex:i];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 60);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[scrollView addSubview:button];
if (column == 4) {
column = 0;
row++;
} else {
column++;
}
}
[scrollView setContentSize:CGSizeMake(330, (row+1) * 60 + 10)];
}
- (void) createScrollView2 {
self.slotBg2 = [[UIView alloc] initWithFrame:CGRectMake(362, 370, 300, 143)];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.slotBg.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor grayColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[self.slotBg.layer insertSublayer:gradient atIndex:0];
[self.view addSubview:self.slotBg];
UIScrollView *scrollView2 = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,134.0f)];
[slotBg addSubview:scrollView2];
int row = 0;
int column = 0;
for(int i = 0; i < _thumbs2.count; ++i) {
UIImage *thumb = [_thumbs2 objectAtIndex:i];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*60+10, row*60+10, 60, 60);
[button setImage:thumb forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked2:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[scrollView2 addSubview:button];
if (column == 4) {
column = 0;
row++;
} else {
column++;
}
}
[scrollView2 setContentSize:CGSizeMake(330, (row+1) * 60 + 10)];
}
- (IBAction)buttonClicked:(id)sender {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSInteger slotBG = [prefs integerForKey:#"integerKey"];
if(slotBG == 1){
UIButton *button = (UIButton *)sender;
[button removeFromSuperview];
[_images objectAtIndex:button.tag];
[_images removeObjectAtIndex:button.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%lu.png", button.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
} else if (slotBG == 2){
UIButton *button = (UIButton *)sender;
[button removeFromSuperview];
[_images objectAtIndex:button.tag];
[_images removeObjectAtIndex:button.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"firstSlotImages%lu.png", button.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
} else if (slotBG == 3){
UIButton *button = (UIButton *)sender;
[button removeFromSuperview];
[_images objectAtIndex:button.tag];
[_images removeObjectAtIndex:button.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%lu.png", button.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
}
}
- (IBAction)buttonClicked2:(id)sender {
UIButton *button2 = (UIButton *)sender;
[button2 removeFromSuperview];
[_images2 objectAtIndex:button2.tag];
[_images2 removeObjectAtIndex:button2.tag];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"secondSlotImages%lu.png", button2.tag]];
[fileManager removeItemAtPath: fullPath error:NULL];
NSLog(#"image removed");
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSInteger slotBG = [prefs integerForKey:#"integerKey"];
if(slotBG == 1){
[mode1 setHighlighted:YES];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
[self createScrollView];
} else if(slotBG == 2 ){
[mode2 setHighlighted:YES];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"firstSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
[self createScrollView];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"secondSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage2:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images2 count]);
[self createScrollView2];
} else if( slotBG == 3){
[mode3 setHighlighted:YES];
for(int i = 0; i <= 100; i++)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"oneSlotImages%d.png", i]];
NSLog(#"savedImagePath=%#",savedImagePath);
if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
[self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
NSLog(#"file exists");
}
}
NSLog(#"Count : %d", [_images count]);
[self createScrollView];
}
}
In your createScrollView2 method, you alloc self.slotBg2, but then only reference self.slotBg when adding to your view. Then you add your scrollview2 to the original slotBg.
I have an addToFavourites function, which is causing an EXC_BAD_ACCESS error.
Basically, I have the Favourites View Controller with a list of all the favourites which the user has added previously, now when clicking on one of the favourites, it pushes the view to a detailViewController, this works fine. On the detail view controller, I have an add to favourites button, this button changes to a remove from favourites if it detects that the key already exists in the addToFavourites dictionary. The problem occurs when the user accesses this detailViewController from the favourites page and also from the main page which lists all the detailViews. They are able to do this as I have a tab bar.
So say I am in the detailView accessed through the favourites page, the favourites button has "remove from favourites", this is correct. But then say I click the remove from favourites button, the button changes to "add to favourites" and removes it from the dictionary. All working fine so far. Now when I switch over to the same detailView, but this time accessed from a different tab on the tab bar, firstly the favourites button still reads "remove from favourites" and when I click this button the first time, it changes to "add to favourites", then when I click it again, I get this EXC_BAD_ACCESS error.
Here is the addToFavouritesFunction:
- (IBAction)addToFavourites:(id)sender {
NSString *type = [[NSUserDefaults standardUserDefaults]objectForKey:#"type"];
if(type == #"v") {
NSString *area = [[NSUserDefaults standardUserDefaults]objectForKey:#"area"];
NSString *ID1 = [[NSUserDefaults standardUserDefaults]objectForKey:#"ID1"];
if([[addToFavouritesDictionary allKeys] containsObject:ID1]) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"/SavedDict.data"];
[addToFavouritesDictionary removeObjectForKey:ID1];
[favouritesButton setTitle:#"+ Favourites" forState:(UIControlState)UIControlStateNormal];
[addToFavouritesDictionary writeToFile:filePath atomically: YES];
NSLog(#"New Dictionary: %#", addToFavouritesDictionary);
} else {
NSString *ID1 = [[NSUserDefaults standardUserDefaults]objectForKey:#"ID1"];
[addToFavouritesDictionary setObject:Name forKey:ID1];
[favouritesButton setTitle:#"- Favourites" forState:(UIControlState)UIControlStateNormal];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"/SavedDict.data"];
[addToFavouritesDictionary writeToFile:filePath atomically: YES];
NSLog(#"Mutable Dictionary: %#", addToFavouritesDictionary);
//[addToFavouritesDictionary release];
}
} else {
//NSString *area = [[NSUserDefaults standardUserDefaults]objectForKey:#"area"];
NSString *ID2 = [[NSUserDefaults standardUserDefaults]objectForKey:#"ID2"];
if([[addToFavouritesDictionary allKeys] containsObject:ID2]) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"/SavedDict.data"];
[addToFavouritesDictionary removeObjectForKey:ID2];
[favouritesButton setTitle:#"+ Favourites" forState:(UIControlState)UIControlStateNormal];
[addToFavouritesDictionary writeToFile:filePath atomically: YES];
NSLog(#"Dictionary: %#", addToFavouritesDictionary);
} else {
NSString *ID2 = [[NSUserDefaults standardUserDefaults]objectForKey:#"ID2"];
[addToFavouritesDictionary setObject:Name forKey:ID2];
[favouritesButton setTitle:#"- Favourites" forState:(UIControlState)UIControlStateNormal];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"/SavedDict.data"];
[addToFavouritesDictionary writeToFile:filePath atomically: YES];
NSLog(#"Mutable Dictionary: %#", addToFavouritesDictionary);
}
}
}
Thanks for any help!
Check with debugger whether it shows crashing line exactly ...and set breakpoint after that to check for value
Well...either your addToFavouritesDictionary object or your Name object has been deallocated. How are you creating these objects? Either you are releasing them before you should, or you haven't retained them in the first place.
Objective-C Memory Management
You should probably not be using the line:
if(type == #"v") {
What you are doing here is comparing the pointer for the variable type to the pointer for the string #"v". Instead, you should use a method that compares the contents of the string:
if ([type isEqualToString:#"v") {
EDIT
The easiest way to keep your titles the same would be to store the text in NSUserDefaults. You could do something like below whenever the button is pressed:
// For "Add to Favorites"
[[NSUserDefaults standardUserDefaults] setObject:#"+ Favorites" forKey:#"ButtonState"];
// For "Remove from Favorites"
[[NSUserDefaults standardUserDefaults] setObject:#"- Favorites" forKey:#"ButtonState"];
Then you would execute something like this when the view loads:
[favoritesButton setTitle:(NSString*)[[NSUserDefaults standardUserDefaults] objectForKey:#"ButtonState"] forState:UIControlStateNormal];