简体   繁体   中英

App crashes when attempting to type on UISearchDisplayController

For some reason, my app crashes when ever I attempt to type on UISearchDisplayController . I have used the code needed from here , but I can't seem to find the solution.

Here is the code:

ViewController.h

// #import SideSwipeTableViewController.h
// #import ...

@interface ViewController : SideSwipeTableViewController {

...
UITableView *table;
NSArray *buttonData;
NSMutableArray *buttons;
NSMutableArray *_cloudItems;
...
}

// ...some more code
@end

ViewController.m

// code...

_cloudItems = [[NSMutableArray alloc] initWithObjects:@"The quick brown fox jumped over the lazy dog", @"foo", @"bar", @"Cookies", @"1234567890", nil];

...some more code

@end    

SearchViewController.h

#import "ViewController.h"

@interface SearchViewController : ViewController <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UISearchDisplayDelegate> {

UISearchDisplayController *searchBarController;
UISearchDisplayController *searchResultsController;
NSArray *searchResults;
NSArray *allItems;


}



@property (retain, nonatomic) IBOutlet UISearchDisplayController *searchBarController;
@property (retain, nonatomic) IBOutlet UISearchDisplayController *searchResultsController;
@property (nonatomic, copy) NSArray *searchResults;
@property (nonatomic, copy) NSArray *allItems;
@end

SearchViewController.m

    #import "SearchViewController.h"
    #import "SideSwipeTableViewCell.h"
    #import "ViewController.h"

    #define BUTTON_LEFT_MARGIN 29.3
    #define BUTTON_SPACING 29.3


    @interface SearchViewController (PrivateStuff)
    -(void) setupSideSwipeView;
    -(UIImage*) imageFilledWith:(UIColor*)color using:(UIImage*)startImage;
    @end

    @implementation SearchViewController

    @synthesize searchBarController;
    @synthesize searchResultsController;
    @synthesize searchResults;
    @synthesize allItems;



    - (void)viewDidLoad
    {
        [super viewDidLoad];


        self.table.scrollEnabled = YES;

        // Show buttons when side is swiped

        buttonData = [[NSArray arrayWithObjects:
                      [NSDictionary dictionaryWithObjectsAndKeys:@"Reply", @"title", @"reply.png", @"image", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"Retweet", @"title", @"retweet-outline-button-item.png", @"image", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"Favorite", @"title", @"star-hollow.png", @"image", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"Profile", @"title", @"person.png", @"image", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"Links", @"title", @"paperclip.png", @"image", nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"Action", @"title", @"action.png", @"image", nil],
                   nil] retain];

        // Declares buttons when side is swiped

        buttons = [[NSMutableArray alloc] initWithCapacity:buttonData.count];

        self.allItems = _cloud;

        [self.table reloadData];


        self.sideSwipeView = [[[UIView alloc] initWithFrame:CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y, tableView.frame.size.width, tableView.rowHeight)] autorelease];
    [self setupSideSwipeView];
    }



    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

        NSInteger rows = 0;

        if ([table isEqual:self.searchDisplayController.searchResultsTableView]){
            rows = [self.searchResults count];
        }
        else{
            rows = [allItems count];
        }

        return rows;
    }

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        return 55;
    }

    #pragma mark Generate the side-swiping
    - (void) setupSideSwipeView
    {
        // Add the background pattern
        self.sideSwipeView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"dotted-pattern.png"]];

        // Overlay a shadow image that adds a subtle darker drop shadow around the edges
        UIImage* shadow = [[UIImage imageNamed:@"inner-shadow.png"] stretchableImageWithLeftCapWidth:0 topCapHeight:0];
        UIImageView* shadowImageView = [[[UIImageView alloc] initWithFrame:sideSwipeView.frame] autorelease];
        shadowImageView.alpha = 0.6;
        shadowImageView.image = shadow;
        shadowImageView.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        [self.sideSwipeView addSubview:shadowImageView];

        // Iterate through the button data and create a button for each entry
        CGFloat leftEdge = BUTTON_LEFT_MARGIN;
        for (NSDictionary* buttonInfo in buttonData)
        {
            // Create the button
            UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];

            // Make sure the button ends up in the right place when the cell is resized
            button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;

            // Get the button image
            UIImage* buttonImage = [UIImage imageNamed:[buttonInfo objectForKey:@"image"]];

            // Set the button's frame
            button.frame = CGRectMake(leftEdge, sideSwipeView.center.y - buttonImage.size.height/2.0, buttonImage.size.width, buttonImage.size.height);

            // Add the image as the button's background image
            // [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
            UIImage* grayImage = [self imageFilledWith:[UIColor colorWithWhite:0.0 alpha:1.0] using:buttonImage];
            [button setImage:grayImage forState:UIControlStateNormal];

            // Add a touch up inside action
            [button addTarget:self action:@selector(touchUpInsideAction:) forControlEvents:UIControlEventTouchUpInside];

            // Keep track of the buttons so we know the proper text to display in the touch up inside action
            [buttons addObject:button];

            // Add the button to the side swipe view
            [self.sideSwipeView addSubview:button];

            // Move the left edge in prepartion for the next button
            leftEdge = leftEdge + buttonImage.size.width + BUTTON_SPACING;
        }
    }


#pragma mark Generate TableView
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *cellId = @"Cell";
    UILabel *itemName;

    SideSwipeTableViewCell *cell = (SideSwipeTableViewCell*)[theTableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil)
    {
        cell = [[[SideSwipeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId] autorelease];
        CGRect frame = {{cell.indentationWidth, 0}, { 280.0 , cell.frame.size.height}};
        itemName = [[[UILabel alloc] initWithFrame:frame] autorelease];
        [[cell contentView] addSubview:itemName];
        //  [itemName setTag:1001];
        [itemName setBackgroundColor:[UIColor clearColor]];


        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.detailTextLabel.backgroundColor = [UIColor clearColor];

        cell.textLabel.font = [UIFont fontWithName:@"Futura-Medium" size:18];
        cell.detailTextLabel.font = [UIFont fontWithName:@"Futura-Medium" size:13];
    } else {
        itemName = (UILabel *)[cell viewWithTag:1001];
    }

    // Configure cell

    // Sets the text for the cell
    NSDictionary *dictItem = [allItems objectAtIndex:indexPath.row];
    NSString *name = (NSString *)[dictItem objectForKey:@"name"];
    //NSString *url = (NSString *)[dictItem objectForKey:@"redirect_url"];

    NSDictionary *dictItemResults = [self.searchResults objectAtIndex:indexPath.row];
    NSString *nameResults = (NSString *)[dictItemResults objectForKey:@"name"];
    //NSString *urlResults = (NSString *)[dictItemResults objectForKey:@"redirect_url"];

    if ([table isEqual:self.searchDisplayController.searchResultsTableView]){
        cell.textLabel.text = [NSString stringWithFormat:@"%@", nameResults];
    }
    else{
        cell.textLabel.text = [NSString stringWithFormat:@"%@", name];
    }


    cell.supressDeleteButton = ![self gestureRecognizersSupported];

    cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"cell_background_viewcontroller.png"]];
    tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    tableView.separatorColor = [UIColor grayColor];

    return cell;

}

- (void)filterContentForSearchText:(NSString*)searchText
                             scope:(NSString*)scope
{
    NSPredicate *resultPredicate = [NSPredicate
                                    predicateWithFormat:@"SELF contains[cd] %@",
                                    searchText];

    self.searchResults = [allItems filteredArrayUsingPredicate:resultPredicate];
}

#pragma mark - UISearchDisplayController delegate methods
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]];

    return YES;
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchScope:(NSInteger)searchOption
{
    [self filterContentForSearchText:[self.searchDisplayController.searchBar text]
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:searchOption]];

    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    // If row is deleted, remove it from the list.
    /*   if (editingStyle == UITableViewCellEditingStyleDelete)
     {
     // delete your data item here
     // Animate the deletion from the table.
     [self.table deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
     } */
}


#pragma mark Generate images with given fill color
// Convert the image's fill color to the passed in color
-(UIImage*) imageFilledWith:(UIColor*)color using:(UIImage*)startImage
{
    // Create the proper sized rect
    CGRect imageRect = CGRectMake(0, 0, CGImageGetWidth(startImage.CGImage), CGImageGetHeight(startImage.CGImage));

    // Create a new bitmap context
    CGContextRef context = CGBitmapContextCreate(NULL, imageRect.size.width, imageRect.size.height, 8, 0, CGImageGetColorSpace(startImage.CGImage), kCGImageAlphaPremultipliedLast);

    // Use the passed in image as a clipping mask
    CGContextClipToMask(context, imageRect, startImage.CGImage);
    // Set the fill color
    CGContextSetFillColorWithColor(context, color.CGColor);
    // Fill with color
    CGContextFillRect(context, imageRect);

    // Generate a new image
    CGImageRef newCGImage = CGBitmapContextCreateImage(context);
    UIImage* newImage = [UIImage imageWithCGImage:newCGImage scale:startImage.scale orientation:startImage.imageOrientation];

    // Cleanup
    CGContextRelease(context);
    CGImageRelease(newCGImage);

    return newImage;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [searchResultsController release];
    [searchBarController release];
    [buttonData release];
    [allItems release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setSearchResultsController:nil];
    [self setSearchBarController:nil];
    [super viewDidUnload];
}
@end

This may also be useful to you:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:
(0x392502a3 0x3313f97f 0x3919ae8d 0xe2869 0x323cd545 0x323b230b 0x324cb1b9 0x324eb783 0x3244fd3d 0x324e8ff9 0x324e093b 0x324e08f7 0x32472487 0x324aa22d 0x324a9abd 0x391a1037 0x33fa4d91 0x34efc1b5 0x350ced3b 0x350d0ed3 0x350d0ded 0x350d0ccf 0x350c64ad 0x350d0c0d 0x350d091f 0x350d03af 0x350d0207 0x350d00e5 0x34e9978d 0x34e99105 0x34e98d5f 0x34e98d21 0x34e98c53 0x35050ce7 0x350cfefb 0x350cfe2d 0x39787689 0x350c51db 0x397ad5ef 0x324e5039 0x324e4ff1 0x324b2149 0x324b0041 0x324af8af 0x324ae3a5 0x324ad72f 0x323955f1 0x32382801 0x3238211b 0x375655a3 0x375651d3 0x39225173 0x39225117 0x39223f99 0x39196ebd 0x39196d49 0x375642eb 0x323d62f9 0x9dde7 0x9b4d8)
libc++abi.dylib: terminate called throwing an exception

How would I fix this? I hope I've given enough information. Any help is appreciated. Thanks in advance.

UPDATE:

If I populate an NSArray within SearchViewController.m ,...

_cloud = [[NSMutableArray alloc] initWithObjects:@"The quick brown fox jumped over the lazy dog", @"foo", @"bar", @"Cookies", @"1234567890", nil];

... I get a different error:

 -[__NSCFConstantString objectForKey:]: unrecognized selector sent to instance 0x1659d4
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString objectForKey:]: unrecognized selector sent to instance 0x1659d4'
*** First throw call stack:
(0x392502a3 0x3313f97f 0x39253e07 0x39252531 0x391a9f68 0xac743 0x323cd545 0x323b230b 0x324cb1b9 0x324eb783 0x3244fd3d 0x324e8ff9 0x324e093b 0x324e08f7 0x32472487 0x324aa22d 0x324a9abd 0x391a1037 0x33fa4d91 0x34efc1b5 0x350ced3b 0x350d0ed3 0x350d0ded 0x350d0ccf 0x350c64ad 0x350d0c0d 0x350d091f 0x350d03af 0x350d0207 0x350d00e5 0x34e9978d 0x34e99105 0x34e98d5f 0x34e98d21 0x34e98c53 0x35050ce7 0x350cfefb 0x350cfe2d 0x39787689 0x350c51db 0x397ad5ef 0x324e5039 0x324e4ff1 0x324b2149 0x324b0041 0x324af8af 0x324ae3a5 0x324ad72f 0x323955f1 0x32382801 0x3238211b 0x375655a3 0x375651d3 0x39225173 0x39225117 0x39223f99 0x39196ebd 0x39196d49 0x375642eb 0x323d62f9 0x67c9f 0x65390)
libc++abi.dylib: terminate called throwing an exception
[_cloudItems release];

// Show buttons when side is swiped

[[NSArray arrayWithObjects:
              [NSDictionary dictionaryWithObjectsAndKeys:@"Reply", @"title", @"reply.png", @"image", nil],
              [NSDictionary dictionaryWithObjectsAndKeys:@"Retweet", @"title", @"retweet-outline-button-item.png", @"image", nil],
              [NSDictionary dictionaryWithObjectsAndKeys:@"Favorite", @"title", @"star-hollow.png", @"image", nil],
              [NSDictionary dictionaryWithObjectsAndKeys:@"Profile", @"title", @"person.png", @"image", nil],
              [NSDictionary dictionaryWithObjectsAndKeys:@"Links", @"title", @"paperclip.png", @"image", nil],
              [NSDictionary dictionaryWithObjectsAndKeys:@"Action", @"title", @"action.png", @"image", nil],
               nil] retain];

Seems like this is the culprit. Why are you releasing that array on the viewDidLoad? It looks like this is supposed to be:

_cloudItems = [[NSArray alloc] initWithObjects:[<dictionaries go here>]];

Don't put the retain at the end for this, the alloc will retain it.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM