tags:

views:

34

answers:

2

i have this array called favorites referenced in my app delegate. When i access it in the view controller i use this code

MultiViewAppDelegate *app = (MultiViewAppDelegate *)[[UIApplication sharedApplication] delegate];
    [app.favoritesArray addObject:@"one"];

And in the table thats supposed to display this information im trying to ask if the array contains a certain element and if it does to display that item using this code.

NSLog (@"2");
favoritesArray = [[NSMutableArray alloc]init];

didContain = [[NSMutableArray alloc]init];

NSLog (@"3");

if ([favoritesArray containsObject:@"one"])

{[didContain addObject:@"one"];
NSLog (@"4"); }

however the code isnt running after nslog 3... can someone inform me why?

A: 

Check if favoritesArray in your delegate is initialized. If it is nil, the condition will never be true.

Nikolai Ruhe
what do u mean initiliazed?
Alx
i have it under - (void)applicationDidFinishLaunching:(UIApplication *)application { [window addSubview:tabBarController.view]; favoritesArray = [[NSMutableArray alloc]init];however what do i need to add the array in both of the headers and synthesize it ?
Alx
+2  A: 

Firstly,

NSLog (@"2");
favoritesArray = [[NSMutableArray alloc]init];

The above line will reset your favoritesArray. It will also leak the old one.

didContain = [[NSMutableArray alloc]init];

NSLog (@"3");

if ([favoritesArray containsObject:@"one"])

Here, you're simply asking an empty array if it contains something, which it obviously doesn't.

{[didContain addObject:@"one"];
NSLog (@"4"); }

Which is why none of the above ever happens.

Instead of resetting it, make sure it's set instead.

if (favoritesArray != nil && 
    [favoritesArray containsObject:@"one"]) {
    NSLog(@"yay, it had one in it");
} else {
    NSLog(@"it's nil or it didn't have one in it");
}

You probably don't need favoritesArray != nil, but I put it in because you might have put your alloc-init stuff in because you sometimes get a nil value here. Unlikely though.

if ([favoritesArray containsObject:@"one"]) {
    // contains "one"
}

That should probably do it.

Kalle
If `favoritesArray` is nil then `[favoritesArray containsObject:@"one"]` will always return NO, so you are correct when you say the nil check isn't necessary.
Kevin Ballard