This approach worked for me, and I think it is correct. So far this is the easiest and fastest way to transfer data between the scenes I found.
1. Basic information about userData:
1.1. Hold the apple "Command Key" and click the left mouse button (in Xcode) in the line "userData" (for example, "self". UserData strong>; "). You will receive the following information:
1,2. Visit apple docs: userData
1.3 userData is an NSMutableDictionary, which is basically a special array. In addition to the value, it contains a key associated with the value. With this key you can find the values. It may also be useful: apple docs: NSMuttableDictionary
2. Solution:
2.1. firstScene
//somewhere in firstScene.m //how the tranisiton from firstScene to secondScene is going to look and how long it is goint to take SKTransition *reveal = [SKTransition moveInWithDirection:SKTransitionDirectionDown duration:0.5]; SKView * skView = (SKView *)self.view; SKScene *secondScene = [WBMGameEndsScene sceneWithSize:skView.bounds.size]; //You need to initialize the NSMD since it is by default nil. secondScene.userData = [NSMutableDictionary dictionary];
Here I refer to userData of secondScene, adding an object that is my account. For the purpose it is only 6. I will add my account instance variable. You can add whatever you want as it accepts objects of type "id". The key is important. You will use it in secondScene.m to access the value of the object from then on. Make sure you are not mistaken.
[secondScene .userData setObject:@"6" forKey:@"score"]; //Testing NSLog(@"Is it finally working -- %@",[secondScene .userData objectForKey:@"score"]); //The secondScene will scale to fit the whole SKView secondScene.scaleMode = SKSceneScaleModeAspectFill; //present the secondScene [self.scene.view presentScene: secondScene transition:reveal];
* WBMGameEndsScene is my secondScene. I created it in Xcode with "File - New File ..." as: SKScene. It will contain userData shown below.
2.2. secondScene
//secondScene.m ( ex. in my :"@implementation WBMGameEndsScene")
The following lines of code verify that the value is added correctly:
-(void)didMoveToView:(SKView *)view { NSLog(@"-- -(void)willMoveFromView:(SKView *)view --"); NSLog(@"Working score is : %@",[self.userData valueForKey:@"score"]); NSLog(@"Working score is : %@",[self.userData objectForKey:@"score"]); }
Console output:
2014-03-12 15:29:06.804 AppTest[4841:60b] -(id)initWithSize:(CGSize)size 2014-03-12 15:29:06.806 AppTest[4841:60b] scoreLabel 2014-03-12 15:29:06.812 AppTest[4841:60b] successMessage 2014-03-12 15:29:06.815 AppTest[4841:60b] Is it finally working -- 6 2014-03-12 15:29:06.815 AppTest[4841:60b] -- -(void)willMoveFromView:(SKView *)view -- 2014-03-12 15:29:06.816 AppTest[4841:60b] Working score is : 6 2014-03-12 15:29:06.816 AppTest[4841:60b] Working score is : 6
If I have something wrong, please correct me :). Specifications: iOS 7.0, version Xcode 5.1 (5B130a), OS X 10.9.2