Reputation: 1754
I am trying to create a global array in my app which can be accessed by ALL view controllers. I have put the code in the AppDelegate and then imported the AppDelegate in to the view controller files.
Within the app delegate, I have created an array in the didFinishLaunchingWithOptions:
function. However, I need to create a new function in the AppDelegate which I can then call from other view controllers to filter this global array. So far I have this:
// Function to get suggested foods
- (BOOL)getFood:inCategory(NSString *)foodCat
{
NSMutableArray *filteredArray=[[foodArrayMain filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(foodCat==%@)",foodCat]] mutableCopy];
return filteredArray;
}
However, I know there are errors here and it doesn't seem to work. I have tried calling it in one of the other view controllers like this:
NSArray *foods= [AppDelegate getFood:@"meats"];
Any help?
Upvotes: 0
Views: 231
Reputation: 677
First step would be to change the ReturnValue from:
- (BOOL)getFood:inCategory(NSString *)foodCat
to:
- (NSMutableArray *)getFood:inCategory(NSString *)foodCat
Also: I wouldn't use AppDelegate for this. I is not really good style.
Another way would be to use a propertyList in your app's document folder and use that to serialise/deserialise the array information.
Upvotes: 0
Reputation: 13713
You need to use the AppDelegate
instance rather than the AppDelegate
class (since your method is an instance method) :
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedInstance].delegate;
NSArray *foods = [appDelegate getFood:@"meats"];
As Amandir mentioned change the return value of your method to NSArray *
since that is the type of the value you are returning from this method. (Or use NSMutableArray * if you intend to modify the array by the calling class or anywhere else)
A more suitable approach will be to define a singleton class which manages your global settings/data.
Upvotes: 1