views:

57

answers:

2

how is it possible to save an array in multiple locations ie. different view controllers in order to save the data in the arrays and allow it to be used afterwards by a table? edit

objective c i have an ibaction with code

[[NSMutableArray alloc] init];
[favoritesArray addObject: @"one"]; 
//and in the fav table view this code//
favoritesArray = [[NSMutableArray alloc]init];
didContain = [[NSMutableArray alloc]init];
if ([favoritesArray contains:@"one"]);

{ [didContain addObject:@"trial"]; }

however its crashing at the if part...

+1  A: 

Alx, are you trying to access the data in favouritesArray from multiple objects? This is what I think you are trying to do, but without more context it is difficult to suggest a solution. Here is one possible approach:

Declare favouritesArray as a property in your controller class. (You could use @property and @synthesize to achieve this.)

Then, in your views, add your controller as an IBOutlet (called, say, myController). Then make connections in Interface Builder between your view and the controller. You will then be able to access the array from your view classes by writing:

[[myController favouritesArray] objectAtIndex:3], for example.

In general, it is a bad idea to 'copy' data between different objects in your program. Unless there's a very good reason to do this, use references instead. Try to think about what object is the 'owner' for that array, and put it in that class.

Tim Kemp
+1  A: 
[[NSMutableArray alloc] init];
[favoritesArray addObject: @"one"]; 

I assume you actually have the “favoritesArray =” in the original code, and simply missed it when copying. Otherwise, you're dropping the array on the floor and favoritesArray still holds nil.

if ([favoritesArray contains:@"one"]);

{ [didContain addObject:@"trial"]; }

however its crashing at the if part...

There are two problems with your if statement:

  1. NSArray does not respond to contains:, which is what the crash is telling you. You need to send your array a message it does respond to, such as containsObject:, which is listed in the documentation.
  2. As I indicated through the formatting I applied to your code, the if statement does not relate to the { [didContain addObject:@"trial"]; } statement that follows it.

    That's because you put a semicolon after the if condition. An if statement does not take a semicolon between the condition and the statement; the statement must directly follow the condition (i.e. be immediately after the )). Moreover, a semicolon by itself is a valid, empty statement.

    So, you have an empty statement subject to the if (if the favorites array contains @"one", do nothing), and you have the statement you meant to have controlled by the if standing on its own, unconditional.

    Cut out the semicolon after the if so that the { … } binds to the if instead of being a separate statement.

Peter Hosey
thanks the semicolon and the containsObject fixed it thanks
Alx