views:

1035

answers:

2

I have a question about sharing data between views, hopefully it's not too basic. I have an NSMutableArray in an appDelegate with say (Object1, Object2, Object3). When a new Object is created (and added to the array), I need to access that Object on the next view. Previously I was just passing the Object to the next view, but that got messy and seemed wrong.

So now I have all my objects in one place, but how can I access the Object (that was just created) in the next view because I don't know what index it was added into? Do I need to check the count of the array each time I create an object, then determine the array index from that and pass that index value to the next view? Or is there a way to retrieve objects from a NSMutable array by a unique name of some sort?

Another solution would be to iterate over all of the Objects until I find the one that I want, but I'm wondering what is the right way to do this. Thank you for your time.

Edit: Thanks for the response, I'll clarify what I'm trying to do. I have a NavigationController and each view that you go into needs access to the Object. You could think about it like a book. The first view you select the book you want to read, and then each view thereafter is a page from the book you selected. And in the App Delegate is the array of all the books. Would you pass each "Page" view the book?

Keep in mind this is kind of a rough example because when you select the book you would already know the index that it was at. Say if you create a book, then you don't know where in the array it is at yet.

+2  A: 

I'm not exactly sure if you're talking about sharing objects among different controls, or if you're talking about different view controllers - like a master-detail view, although I suspect this is what you mean.

In this case, if you have a detail view dedicated to editing a single object, it's not, in my opinion, wrong to give that view controller an object to edit. If you're maintaining an array, you could still add the new object to the array, and assign the object to the new view controller before your put it on screen.

If you could be a little more specific about how your application works, I might be able to give you some better help.

Alex
Thanks Alex for trying to decrypt what I meant. I added some clarification, but I think an NSMutableDictionary will do the job.
Sean
+1  A: 

If you can create a meaningful unique name for each of those objects, just use a NSMutableDictionary and have the controllers get to the data by specifying the key. Like so:

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSString *obj = [appDelegate.dict objectForKey:@"unique-name-here"];

Hope that helps.

jpm
I think this is what I'm really looking for. Thank you!
Sean