Deleting in NSDocumentDirectory and UIScrollView

安稳与你 提交于 2020-01-15 03:14:06

问题


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)];
            }

        }
    }
}

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12188281/deleting-in-nsdocumentdirectory-and-uiscrollview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!