(For passing values between viewcontrollers) the simplest and most professional method is the so-called shared instance ). The basic practice is to create a singleton class method that can instantiate this class at the first call, and then return this instance in the next call.
We use a common engine class in a board game as an example:
Engine. h
[Plain]View plaincopy
- # Import
-
- @ Interface Engine: nsobject {
-
- Nsuinteger Board [2, 100]; // C-style array
-
- }
-
- + (Engine *) sharedinstance;
-
-
- -(Nsuinteger) getfieldvalueatpos :( nsuinteger) X;
- -(Void) setfieldvalueatpos :( nsuinteger) x tovalue :( nsuinteger) newval;
-
-
- @ End
Engine. m
[Plain]View plaincopy
-
- # Import "engine. H"
-
- @ Implementation engine
-
-
- Static engine * _ sharedinstance;
-
- -(ID) Init
-
- {
-
- If (Self = [Super init])
-
- {
- // Custom Initialization
-
- Memset (board, 0, sizeof (board ));
-
- }
-
- Return self;
- }
-
-
- + (Engine *) sharedinstance
-
- {
- If (! _ Sharedinstance)
-
- {
-
- _ Sharedinstance = [[engine alloc] init];
-
- }
-
- Return _ sharedinstance;
-
- }
-
- -(Nsuinteger) getfieldvalueatpos :( nsuinteger) x
-
- {
-
- Return Board [x];
-
- }
-
- -(Void) setfieldvalueatpos :( nsuinteger) x tovalue :( nsuinteger) newval
-
- {
-
- Board [x] = newval;
- }
-
-
- @ End
Then we only need to import this class to our app delegate and add the following lines at the same timeCode:
[Plain]View plaincopy
-
- // At the top: # import "engine. H"
-
- Engine * myengine = [engine sharedinstance];
-
-
- [Myengine setfieldvalueatpos: 3 tovalue: 1];
-
- Nslog (@ "POS 3: % d", [myengine getfieldvalueatpos: 3]);
-
- Nslog (@ "POS 2: % d", [myengine getfieldvalueatpos: 2]);
You will find that you do not have the alloc-init class, but keep getting the sharedinstance pointer. In fact, this class method will create an instance during the first call and store it in static variables.
You don't have to worry about release, because the memory occupied by all apps will be cleared when they exit. But if you want to do better, you can put the sharedinstance release into the dealloc method of APP delegate. However, I found that this dealloc has never been called. I guess it is because IOS thinks that kill this app and releasing memory space will be faster.
You can also put other methods and data variables related to the engine class into the engine class. Just don't add anything about displaying it. In this way, the engine can be reused.