Hrafn
Hrafn

Reputation: 2946

Passing NSMutableArray from one View Controller to a function in another

I've read up on couple of questions here on SO about passing data between two View Controllers and seen different ways suggested of doing it. My problem is as follows:

I have a view controller (lets call it a "A") that has a searchbar in a toolbar. Nothing else. Then I have another view controller ("B") that is responsible for displaying a popover view when the user presses the search button on the keyboard when searching in the searchbar. This all works. The user enters text, presses the search button, the popover is shown. Great.

Now I have yet to display any search results in the popover tableview and am trying to pass a NSMutableArray to a function in B as an argument:

in B.h:

@property (nonatomic, retain) NSMutableArray *searchResults;

in B.m:

    @synthesize searchResults;

     -(void)setSearchResults:(NSMutableArray *)resultArray{
         [self.searchResults removeAllObjects];
         [self.searchResults addObjectsFromArray:resultArray];
     }

in A.h:

#import "B.h"
@property(nonatomic, retain) B *viewControllerObjectB;

in A.m:

@synthesize viewControllerObjectB;

 //The searchResultsArray is passed on from another function
-(void)communicateWithB:(NSMutableArray *)searchResultsArray{

    //I initialize the viewControllerObjectB in here

    NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:searchResultsArray];
    [viewControllerObjectB setSearchResults:temp];
}

Now this all works except I do not get the content of temp passed on into the function in B.m. I'ts empty (nil). This is my problem.

I'm fairly new to iOS so all help would be appreciated.

EDIT: Forgot to mention that I'm using ARC.

Upvotes: 0

Views: 2066

Answers (1)

DarthMike
DarthMike

Reputation: 3481

You didn't initialize your array (that's why it's nil). So in alloc method you should:

- (id)init {
    self = [super init];

     if (self) {
          self.searchResults = [NSMutableArray arrayWithCapacity:10];
     }
}

I also spotted 2 problems in your code:

@synthesize searchResults;

     -(void)setSearchResults:(NSMutableArray *)resultArray{
         //PROPERTY LOGIC IS RETAIN, SO YOU NEED TO RELEASE/RETAIN WHEN YOU OVERRIDE A SETTER
         if (searchResults != resultArray) {
              [searchResults release];
              searchResults = [resultArray retain];
         }
     }


-(void)communicateWithB:(NSMutableArray *)searchResultsArray{

    //I initialize the viewControllerObjectB in here
    //MEM. LEAK ON TEMP
    NSMutableArray *temp = [[[NSMutableArray alloc] initWithArray:searchResultsArray] autorelease];
    [viewControllerObjectB setSearchResults:temp];
}

Upvotes: 1

Related Questions