简体   繁体   中英

NSMutableArray Vs UIView iphone

I have an NSMutableArray in my MainViewController classes.. I added 10 Objects to NSMutableArray.When i Click subview button in my MainViewController classes, I push SubviewController (UIViewController)classes.... In subviewcontroller classes i want to use MainViewController Values of NSMutableArray. And also i Want to add or remove objects from that NSMutableArray...

My aim is I want to use the NSMutableArray Values to all UIViewController classes to my project with an same name of the variable.

If I understand you right - you want to access the NSMutableArray in MainViewController from all your (subview) controllers?

You can store the handle to your MainViewController in all you subviews and access the array using that handle.

I think better idea would be move the data to some globally accessible instance (eg to ApplicationDelegate class or wrap it into singleton class)

What you want to do is add a Cocoa property in your main view controller that references the NSMutableArray instance which you instantiate and populate with elements.

In the header:

@interface MainViewController : UIViewController {
  NSMutableArray *myMutableArray;
}

@property (nonatomic, retain) NSMutableArray *myMutableArray;

@end

In the implementation, add the @synthesize directive and remember to release the array in -dealloc :

@implementation MainViewController

@synthesize myMutableArray;

...

- (void) dealloc {
  [myMutableArray release];
  [super dealloc];
}

@end

You also want to add this property to view controllers that are subordinate to the main view controller, in the exact same way.

In your main view controller, when you are ready to push the subordinate view controller, you set the subordinate view controller's property accordingly:

- (void) pushSubordinateViewController {
  SubordinateViewController *subVC = [[SubordinateViewController alloc] initWithNibName:@"SubordinateViewController" bundle:nil];
  subVC.myMutableArray = self.myMutableArray; // this sets the sub view controller's mutable array property
  [self.navigationController pushViewController:subVC animated:YES];
  [subVC release];
}

Likewise in your subordinate view controller, it will need to set its subordinate's mutable array property accordingly, when it pushes its own view controller.

By setting references in this way, each view controller is pointed at the same mutable array, containing the desired elements.

To use the array, just call self.myMutableArray , eg [self.myMutableArray addObject:object] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM