I have a cocos2d based iphone app with a problem. When the user pauses the game and then hits the resume button, some CCSprites will disappear from the screen.
This behavior is random, no pattern followed. I just know that this only happens when the user resumes the game.
Here is the code, what am I doing wrong?
I first thought it might be a memory management problem, but I never get any EXC_BAD_ACCESS when the user hits resume... So the sprites probably still exist.
The sprites are a property within an object I'll call "myobject".
In myObject.h I have:
#interface myObject : CCNode{
CCSprite *_sprite1,*_sprite2;
// some other code
}
#property (nonatomic,retain) CCSprite *sprite1,*sprite2;
And in myObject.m file:
#synthesize sprite1=_sprite1;
#synthesize sprite2=_sprite2;
+(id)create:(CCLayer*)scene{
myobject.sprite1 = [CCSprite spriteWithFile:spriteFile];
[scene addChild:myobject.sprite1];
// same for sprite2
}
-(void) move:(ccTime)dt{
//SOMECODE
self.sprite1.position=ccp(self.x,self.y); // same for sprite2
}
then they get moved around with a function called on the myobject.
In the main scene, here is how these objects are created and moved around:
myObject *myObject;
NSMutableArray *_myObjects;
#implementation HelloWorld
+(id) scene
{
CCScene *scene = [CCScene node];
HelloWorld *layer = [HelloWorld node];
[scene addChild:layer z:0 tag:33];
return scene;
}
-(id) init
{
if( (self=[super init] )) {
_myObjects = [[NSMutableArray alloc] init];
// some other code
}
}
-(void) addObject(){
myObject=[myObject create:self];
[_fallingObjects addObject:fallingObject];
}
-(void) nextFrame:(ccTime) dt{
for(myObject *theObject in _myObjects){
[theObject move:dt];
}
}
// And here is the function that does the pause/unpause, here it is:
- (void) pauseGame{
if(pauseStatus==0){
[[CCDirector sharedDirector] pause];
pauseStatus=1;
// some code to display menu etc... such as:
[self addChild:pauseMenu z:10];
}
else{
[self removeChild:pauseMenu cleanup:YES];
[self removeChild:scoreLabel cleanup:YES];
[self removeChild:highscoreLabel cleanup:YES];
[self removeChild:titleLabel cleanup:YES];
[self removeChild:pauseLayer cleanup:YES];
[[CCDirector sharedDirector] resume];
pauseStatus=0;
}
}
==EDIT===
I have discovered that this problem is also true for sprites that I add directly to my scene, such as the sprite clown added as shown below:
CCSprite *clown;
#implementation HelloWorld
-(id) init
{
if( (self=[super init] )) {
// some code
clown = [[CCSprite spriteWithFile:#"clown.png"] retain];
[self addChild:clown z:2];
// some more code
}
}
#end
==END OF EDIT===
There's something odd about your setup. FallingObject is a CCNode that contains two sprites. Yet instead of adding the sprites to the FallingObject class (self), and then adding FallingObject to the scene, you are adding the sprites directly to the scene. This leaves the FallingObject node outside of the scene hierarchy.
That's also why you have to do things like updating sprite positions manually which would otherwise require no code at all:
self.sprite1.position=ccp(self.x,self.y);
For what it's worth, I suppose that due to the nonconformity of this setup you may be accidentally moving the sprites outside the screen, or the node either isn't properly paused or resumed.
Related
EDIT:
I added the following code in both the dealloc and cleanup method of the previous scene (the one from which I call replaceScene but it does not have any effect. Even after 1/2/5 seconds from when InstructionScene has being created the memory does still contain the assets from the previous scene. The only way to force the removal of those is to remove them from the new scene 0.1f seconds after the scene is being created (via a Callback). This is kind of weird.
Here is the code of the previous scene cleanup and daelloc methods:
-(void) cleanup
{
CCLOG(#"");
CCLOG(#"");
CCLOG(#"PlanetSelection Menu cleanup");
CCLOG(#"");
[super cleanup];
[planetLayer removeAllChildrenWithCleanup:YES];
[self removeAllChildrenWithCleanup: YES];
[[CCSpriteFrameCache sharedSpriteFrameCache] removeSpriteFramesFromFile:textureFileName];
[[CCTextureCache sharedTextureCache] removeUnusedTextures];
[[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];
[CCAnimationCache purgeSharedAnimationCache];
}
-(void) dealloc
{
CCLOG(#"Dealloc gets caled");
[CCAnimationCache purgeSharedAnimationCache];
[[CCDirector sharedDirector] purgeCachedData];
[[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];
[[CCSpriteFrameCache sharedSpriteFrameCache] removeSpriteFramesFromFile:textureFileName];
}
Original question:
I got several scenes in my game and so far I used the following bit of code at the beginning of each scene to remove previously stored textures. However there is a case in which this doesn't work: when I replace a scene (lets call it A) with a new scene (lets call it B) with no sprites and only some label created from font image sheet.
[[CCDirector sharedDirector] replaceScene: [InstructionsScene sceneWithLevelName:FIRST_LEVEL]];
The new object does get created too fast as the following call doesn't seem to have any effect:
-(id) initWithLevelName:(LevelName)name
{
if ((self = [super init]))
{
//Remove stuff from previous scene
[[CCSpriteFrameCache sharedSpriteFrameCache] removeSpriteFrames];
[[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames]; //Not really necessary
//Use these
[[CCTextureCache sharedTextureCache] removeUnusedTextures]; //Not really needed
[[CCTextureCache sharedTextureCache] removeAllTextures];
[[CCDirector sharedDirector] purgeCachedData];
[CCAnimationCache purgeSharedAnimationCache];
....
}
}
At the moment in which the replace scene method is being called the two CCLayer (CCScane) objects are alive at the same time. However texture from the previous scene do not get removed. The same code works perfectly if a sprite sheet is being added and used in the Instruction scene. A tweak to this is to use a callback to a selector removing all textures after 0.1f, however this is not very elegant and smooth:
[self runAction:[CCSequence actionOne:[CCDelayTime actionWithDuration:0.1f] two:[CCCallFunc actionWithTarget:self selector:#selector(removeStuffFromPreviousScene)]]];
Is this a known issue? It could cause potential crashes.
I paste here the code to make sure you can try it out:
//
// InstructionsScene.h
//
// Created by mm24 on 09/09/13.
// Copyright 2013 mm24. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "CommonEnumerations.h"
#interface InstructionsScene : CCLayer {
LevelName levelName;
float startTime;
CCLabelBMFont * levelNameTitle;
CCLabelBMFont * levelSubtitle;
CCLabelBMFont * instructionsHeader;
CCLabelBMFont * instructions;
}
+(id)sceneWithLevelName:(LevelName)name;
#end
//
// InstructionsScene.m
//
// Created by mm24 on 09/09/13.
// Copyright 2013 mm24. All rights reserved.
//
#import "InstructionsScene.h"
#import "ShooterScene.h"
#import "AppDelegate.h"
#import "mach/mach.h"
#implementation InstructionsScene
+(id)sceneWithLevelName:(LevelName)name
{
CCScene * scene = [CCScene node];
InstructionsScene * layer = [[self alloc] initWithLevelName:name];
[scene addChild:layer];
return scene;
}
-(id) initWithLevelName:(LevelName)name
{
if ((self = [super init]))
{
//Remove stuff from previous scene
[[CCSpriteFrameCache sharedSpriteFrameCache] removeSpriteFrames];
[[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];
//Use these
[[CCTextureCache sharedTextureCache] removeUnusedTextures];
[[CCTextureCache sharedTextureCache] removeAllTextures];
[[CCDirector sharedDirector] purgeCachedData];
[CCAnimationCache purgeSharedAnimationCache];
//Try out and use it. Not compulsory
[self removeAllChildrenWithCleanup: YES];
CCLOG(#"init with level name");
levelName = name;
startTime = 10.0f;
levelNameTitle = [CCLabelBMFont labelWithString:#"Title" fntFile:#"bitmapFontTest.fnt"];
levelNameTitle.position = CGPointMake(160.0f, 420.0f);
levelNameTitle.anchorPoint = CGPointMake(0.5f, 0.5f);
levelNameTitle.scale = 1.3f;
[self addChild:levelNameTitle z:1] ;
levelSubtitle = [CCLabelBMFont labelWithString:#"Subtitle" fntFile:#"bitmapFontTest.fnt"];
levelSubtitle.position = CGPointMake(160.0f, 400.0f);
levelSubtitle.anchorPoint = CGPointMake(0.5f, 0.5f);
levelSubtitle.scale = 0.7f;
[self addChild:levelSubtitle z:1] ;
instructionsHeader = [CCLabelBMFont labelWithString:#" Instructions " fntFile:#"bitmapFontTest.fnt"];
instructionsHeader.position = CGPointMake(160.0f, 240.0f);
instructionsHeader.anchorPoint = CGPointMake(0.5f, 0.5f);
instructionsHeader.scale = 0.7f;
[self addChild:instructionsHeader z:1] ;
instructions = [CCLabelBMFont labelWithString:#"Press any key" fntFile:#"bitmapFontTest.fnt"];
instructions.position = CGPointMake(160.0f, 200.0f);
instructions.anchorPoint = CGPointMake(0.5f, 0.5f);
instructions.scale = 0.7f;
[self addChild:instructions z:1] ;
[[CCDirector sharedDirector] resume];
// [self runAction:[CCSequence actionOne:[CCDelayTime actionWithDuration:0.1f] two:[CCCallFunc actionWithTarget:self selector:#selector(removeStuffFromPreviousScene)]]];
[self runAction:[CCSequence actionOne:[CCDelayTime actionWithDuration:1.0f] two:[CCCallFunc actionWithTarget:self selector:#selector(report_memory)]]];
[self runAction:[CCSequence actionOne:[CCDelayTime actionWithDuration:2.0f] two:[CCCallFunc actionWithTarget:self selector:#selector(report_memory)]]];
[self runAction:[CCSequence actionOne:[CCDelayTime actionWithDuration:5.0f] two:[CCCallFunc actionWithTarget:self selector:#selector(report_memory)]]];
[self callBackReplace];
}
return self;
}
-(void) removeStuffFromPreviousScene
{
//Use these
[[CCSpriteFrameCache sharedSpriteFrameCache] removeSpriteFrames];
[[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];
//Use these
[[CCTextureCache sharedTextureCache] removeUnusedTextures];
[[CCTextureCache sharedTextureCache] removeAllTextures];
[[CCDirector sharedDirector] purgeCachedData];
[CCAnimationCache purgeSharedAnimationCache];
}
-(void) report_memory {
CCLOG(#"");
CCLOG(#"");
CCLOG(#"InstructionScene info:");
CCLOG(#"");
[[CCTextureCache sharedTextureCache] dumpCachedTextureInfo];
struct task_basic_info info;
mach_msg_type_number_t size = sizeof(info);
kern_return_t kerr = task_info(mach_task_self(),
TASK_BASIC_INFO,
(task_info_t)&info,
&size);
if( kerr == KERN_SUCCESS ) {
NSLog(#"Memory in use (in bytes): %u", info.resident_size);
} else {
NSLog(#"Error with task_info(): %s", mach_error_string(kerr));
}
}
-(void) nextSuggestionPressed
{
[self stopAllActions];
[self callBackReplace];
}
-(void) callBackReplace
{
[self runAction:[CCSequence actions:
[CCDelayTime actionWithDuration:startTime] ,
[CCCallFunc actionWithTarget:self selector:#selector(replaceWithShooterScene)],
nil]
];
}
-(void) replaceWithShooterScene
{
[[CCDirector sharedDirector] replaceScene:[ShooterScene sceneWithLevelName:levelName]];
}
#end
Since you initialize the new scene within an already running scene, both scenes are alive at the same time. If you try to remove "unused" resources during init of the new scene, nothing (or not much) will happen since the existing scene is still using these assets.
You can only do two things:
a loading scene in between the two scenes to allow the first scene to deallocate before the next scene is initialized
unloading all unused assets during dealloc of a scene, not when initializing a new one
The loading scene is the best approach if both scenes use a lot of unique assets, so having both in memory at the same time may cause memory warnings or even the app forced to terminate due to memory pressure.
The other approach is best used in all other cases. Just be careful to unload specific resources rather than using the "unused" methods because another scene may currently be using this resource and will be forced to reload it if the other scene removes it.
PS: as long as your app isn't under memory pressure even on devices with the least amount of memory you shouldn't remove resources simply to prevent them from being reloaded again and again. Switching scenes will be a lot faster with already cached textures.
-(void)createSprite{
CCSprite *shotV = [CCSprite spriteWithFile:#"green.png"];
[self addChild:shotV z:1];
[shotVArray addObject:shotV];
NSlog(#"%#",shotV);
}
-(void)aSpecialCase{
[self removeChild:[shotVArray lastObject] cleanup:YES];
}
I'm not getting this to work.
The function "createSprite" spams out sprites. "In aSpecialCase" I want to remove the last sprite that was created. Also hoping that removing it will end the current CCSequence for that instance.
-(void)aSpecialCase{
[self removeChild:[shotVArray lastObject] cleanup:YES];
}
This only removes the sprite from layer.. Doesn't remove it from array itself...
So better way is..
-(void)aSpecialCase{
CCSprite *sprite = [pshotVArray lastObject];
[self removeChild:sprite cleanup:YES];
[pshotVArray removeObject:sprite];
}
Hope this helps.. :)
I am trying to create a Cocoa UI that consists of two sets of squares (chess-like grids) that will assume different colours while an underlying algorithm is running. When the execution of the algorithm comes to an end, the UI should be able to handle clicks, panning and other gestures.
The hierarchy I have so far is the following (please check the attached code for specifics):
1) the main window that is the window of a window controller
2) a split view with two custom views, mainView and sideView (each one would hold a set of squares)
3) two view controllers (mainViewController and sideViewController)
I would like to be able to load the squares as subviews of mainView and sideView.
I thought of having another custom view, say SquareView with another nib file. My questions would be:
a) how do I create this SquareView so that it can be used to create the squares that will be added to mainView and sideView as subviews to form chess-like grids?
b) how do I add subviews to mainView and sideView to built the two grids? For the sake of simplicity, let's assume there would be four non-overlapping squares for each of the previously mentioned views.
Thank you!
MainView.m
#import "MainView.h"
#implementation MainView
- (void)drawRect:(NSRect)TheRect
{
[[NSColor grayColor] set];
[NSBezierPath fillRect:[self bounds]];
}
SideView.m
#import "SideView.h"
#implementation MainView
- (void)drawRect:(NSRect)TheRect
{
[[NSColor whiteColor] set];
[NSBezierPath fillRect:[self bounds]];
}
MainWindowController.h
#import <Cocoa/Cocoa.h>
#class SideViewController;
#class MainViewController;
#interface MainWindowController : NSWindowController
{
IBOutlet NSSplitView* oMainSplitView;
SideViewController* sideViewController;
MainViewController* mainViewController;
}
#end
MainWindowController.m
#import "MainWindowController.h"
#import "SideViewController.h"
#import "MainViewController.h"
#implementation MainWindowController
- (void)windowDidLoad
{
sideViewController = [[SideViewController alloc] initWithNibName:#"SideView" bundle:nil];
NSView* splitViewLeftView = [[oMainSplitView subviews] objectAtIndex:0];
NSView* sideView = [sideViewController view];
[sideView setFrame:[splitViewLeftView bounds]];
[sideView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
[splitViewLeftView addSubview:sideView];
mainViewController = [[MainViewController alloc] initWithNibName:#"MainView" bundle:nil];
NSView* splitViewRightView = [[oMainSplitView subviews] objectAtIndex:1];
NSView* mainView = [mainViewController view];
[mainView setFrame:[splitViewRightView bounds]];
[mainView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
[splitViewRightView addSubview:mainView];
}
You can make this as simple or as complicated as you desire: simple? do everything you want in MainView's drawRect method; complex: nest NSViews (or NSCell's, or NSBox's, etc.) and have each one draw itself.
Personally, I'd vote to keep it simpleā¦
a) I think the easiest way would be to create a matrix of NSBoxes, which you could do in code or in IB. Having the squares in a matrix would make it easy to loop through them or access specific ones.
b) I'm not sure what your question is here -- you would do it just as you did in your posted code, using [mainView addSubview:squareMatrix];
After Edit: Actually, it looks like IB won't let you embed NSBoxes in a matrix. In the past, I've made a matrix of subclassed NSButtonCells (to allow background color with no border) that had a grid of 64x64 cells that were clickable and would change color with those clicks. I don't know if you want a fixed number of cells in your views, or do you need to dynamically change the number? Something like this could work for you I think -- I actually created this in code, because IB was really slow in updating with that many cells.
Here is what I did. In my case, I needed cells with no border but with background color, so I had to subclass NSButtonCell, like this:
-(id)initWithRGBAlpha:(NSArray *)rgbAlpha {
if (self == [super init]) {
NSColor *color = [NSColor colorWithCalibratedRed:[[rgbAlpha objectAtIndex:0]doubleValue]
green:[[rgbAlpha objectAtIndex:1]doubleValue]
blue:[[rgbAlpha objectAtIndex:2]doubleValue]
alpha:[[rgbAlpha objectAtIndex:3]doubleValue]];
[self setBackgroundColor:color];
[self setTitle:#""];
[self setBordered:NO];
[self setTag:0];
[self setImageScaling:3];
return self;
}else{
return nil;
}
}
-(void) setState:(NSInteger)value {
if (value == 1) {
self.backgroundColor = self.selectedColor;
[super setState:value];
}else {
self.backgroundColor = self.backgroundColor;
[super setState:value];
}
}
-(void) setBackgroundColor:(NSColor *)color {
backgroundColor = color;
selectedColor = [color colorWithAlphaComponent:.75];
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[super encodeWithCoder:encoder];
[encoder encodeObject:self.backgroundColor forKey:#"bColor"];
}
- (id)initWithCoder:(NSCoder *)decoder {
[super initWithCoder:decoder];
self.backgroundColor = [decoder decodeObjectForKey:#"bColor"];
return self;
}
I created the matrix in code, like so:
#implementation RDMatrix
-(void) initWithParentView:(NSView *) cv {
NSNumber *one = [NSNumber numberWithInt:1];
NSArray *colors = [NSArray arrayWithObjects:one,one,one,one,nil];
RDButtonCell *theCell = [[RDButtonCell alloc ]initWithRGBAlpha:colors];
[self initWithFrame:NSMakeRect(200,100,1,1) mode:2 prototype:theCell numberOfRows:64 numberOfColumns:64];
[self setSelectionByRect:TRUE];
[self setCellSize:NSMakeSize(8,8)];
[self sizeToCells];
self.target = self;
self.action = #selector(matrixClick:);
self.backgroundColor = [NSColor lightGrayColor];
self.drawsBackground = TRUE;
self.autoresizingMask = 8;
self.allowsEmptySelection = TRUE;
[cv addSubview:self];
}
-(void) matrixClick: (id) sender {
for (RDButtonCell *aCell in self.selectedCells){
if ([self.selectedCells count] < 64) {
aCell.backgroundColor = [NSColor colorWithCalibratedRed:1 green:0 blue:0 alpha:1];
}else{
aCell.backgroundColor = [NSColor colorWithCalibratedRed:0 green:.5 blue:1 alpha:1];
}
}
[self deselectAllCells];
}
#end
I am confused about why this code does not display any image:
In the app delegate:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSRect rect = window.frame;
rect.origin.x = 0;
rect.origin.y = 0;
BlueImageView *blueImageView = [[BlueImageView alloc]initWithFrame:rect];
window.contentView = blueImageView; // also tried [window.contentView addSubview: blueImageView];
}
BlueImageView.h:
#interface BlueImageView : NSImageView {
}
#end
BlueImageView.m:
#implementation BlueImageView
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setImage: [NSImage imageNamed:#"imagefile.png"]];
NSAssert(self.image, #"");
NSLog (#"Initialized");
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect {
}
#end
The file imagefile.png exists. The NSAssert is not causing an exception. The NSLog is firing. But no image shows up in the window.
The drawRect: method is called to draw the view, and your implementation immediately returns. To get NSImageView to draw the image for you, call [super drawRect:dirtyRect]; in your implementation of drawRect:. If you aren't going to do any other drawing in drawRect:, just remove the method to speed up drawing.
Greetings all,
I am a noob and I have been trying to work through this for a few days.
I am adding images to a view via UItouch. The view contains a background on top of which the new images are add. How do I clear the images I am adding from the subview, without getting rid of the UIImage that is the background. Any assistance is greatly appreciated. Thanks in Advance.
here is the code:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event {
NSUInteger numTaps = [[touches anyObject] tapCount];
if (numTaps==2) {
imageCounter.text =#"two taps registered";
//__ remove images
UIView* subview;
while ((subview = [[self.view subviews] lastObject]) != nil)
[subview removeFromSuperview];
return;
}else {
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self.view];
CGRect myImageRect = CGRectMake((touchPoint.x -40), (touchPoint.y -45), 80.0f, 90.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:#"pg6_dog_button.png"]];
myImage.opaque = YES; // explicitly opaque for performance
[self.view addSubview:myImage];
[myImage release];
[imagesArray addObject:myImage];
NSNumber *arrayCount =[self.view.subviews count];
viewArrayCount.text =[NSString stringWithFormat:#"%d",arrayCount];
imageCount=imageCount++;
imageCounter.text =[NSString stringWithFormat:#"%d",imageCount];
}
}
What you need is a way of distinguishing the added UIImageView objects from the background UIImageView. There are two ways I can think of to do this.
Approach 1: Assign added UIImageView objects a special tag value
Each UIView object has a tag property which is simply an integer value that can be used to identify that view. You could set the tag value of each added view to 7 like this:
myImage.tag = 7;
Then, to remove the added views, you could step through all of the subviews and only remove the ones with a tag value of 7:
for (UIView *subview in [self.view subviews]) {
if (subview.tag == 7) {
[subview removeFromSuperview];
}
}
Approach 2: Remember the background view
Another approach is to keep a reference to the background view so you can distinguish it from the added views. Make an IBOutlet for the background UIImageView and assign it the usual way in Interface Builder. Then, before removing a subview, just make sure it's not the background view.
for (UIView *subview in [self.view subviews]) {
if (subview != self.backgroundImageView) {
[subview removeFromSuperview];
}
}
A more swiftly code for approach #1 in only one functional line of code :
self.view.subviews.filter({$0.tag == 7}).forEach({$0.removeFromSuperview()})