Objective c Bool always NO - objective-c

Alright, my mistake, I had previously believed that my ivar was not changing correctly. I was wrong (and got a few downvotes for it). Sorry, the real issue is that i've been calling it incorrectly. I am now posting all the code and i'll let you look at it.
My First class:
classOne.h:
#interface DetailPageController : UIPageViewController
{
BOOL isChromeHidden_;
}
- (void)toggleChromeDisplay;
#end
classOne.m:
#interface DetailPageController ()
#end
#implementation DetailPageController
- (void)toggleChromeDisplay
{
[self toggleChrome:!isChromeHidden_];
}
- (void)toggleChrome:(BOOL)hide
{
//Find chrome value
isChromeHidden_ = !isChromeHidden_;
NSLog(isChromeHidden_ ? #"YES" : #"NO");
}
#end
From the comment's I have received I believe none of that is the actual issue, it's in the following.
classTwo.h: (nothing declared)
classTwo.m:
#interface classTwo ()
#end
#implementation classTwo
//Touches Control
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if ([touch view]) {
if ([touch tapCount] == 2) {
NSLog(#"double touched");
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:#selector(toggleChromeDisplay) object:nil];
}
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if ([touch view]) {
if ([touch tapCount] == 1) {
NSLog(#"single touch");
[self performSelector:#selector(toggleChromeDisplay) withObject:nil afterDelay:0.5];
}
}
}
- (void)toggleChromeDisplay
{
DetailPageController *pageController = [[DetailPageController alloc] init];
[pageController toggleChromeDisplay];
}
#end
Again, sorry for the previous post, I had thought it was an issue with the method but is in fact the way I am calling it.
What I have been forced to do is implement the touching in the controller which handles the area touched but I have the method for the chrome (nav bar and toolbar) in another.
Overall Question
Why is it that every time I call my toggleChromeDisplay method in classTwo, I always get the same NO from my ivar in classOne?
What i've tried for classTwo.h:
#import "DetailPageController.h"
#interface classTwo : UIViewController
{
DetailPageController *detailPageController_;
}
#property (nonatomic, assign) DetailPageController *detailPageController;
#end
My modified code:
In my classTwo.h:
#import "DetailPageController.h"
#interface PhotoViewController : UIViewController
{
DetailPageController *detailPageController_;
}
#property (nonatomic, strong) DetailPageController *detailPageController;
#end
classTwo.m:
#import "classTwo.h"
#interface classTwo ()
#end
#implementation classTwo
#synthesize detailPageController = detailPageController_;
//Touches Control
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if ([touch view]) {
if ([touch tapCount] == 2) {
NSLog(#"double touched");
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:#selector(toggleChromeDisplay) object:nil];
}
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if ([touch view]) {
if ([touch tapCount] == 1) {
NSLog(#"single touch");
[self performSelector:#selector(toggleChromeDisplay) withObject:nil afterDelay:0];
}
}
}
- (void)toggleChromeDisplay
{
[self.detailPageController toggleChromeDisplay];
}
#end

classTwo always instantiates a completely brand new instance of DetailPageViewController before calling toggleChromeDisplay on it, and then it allows it to go out of scope and presumably is deallocated. You need to have it use an instance that's actually alive in your program and controls views in the view hierarchy.
You could add a DetailPageViewController property to classTwo and then your -[classTwo toggleChromeDisplay] implementation would look like:
- (void)toggleChromeDisplay
{
[self.detailPageController toggleChromeDisplay];
}
Again, just make sure to assign to that property the instance of the view controller that's actually on screen. alloc and init are used to creating brand new instances of objects, which won't be the ones that already exist in your application if they've been loaded up, for instance, from a storyboard. So, in your application you probably have a DetailPageViewController instance already that is doing things on the screen and controlling interactions with the user - but your classTwo never is able to message it because again it's creating entirely separate instances of that class. So you need to determine where in your application the DetailPageViewController that's visible on screen is getting instantiated, and at that point ensure your classTwo instance can get a reference to it.
Forgive my repetitiveness, but it is a common mistake I see on Stack Overflow. Just make sure that you understand that while there is one definition of a Class, which is where its instance variables and methods are defined, there can be many separate instances of objects that are created from it (we often say they are instantiated, or created, inited, you'll see a number of terms). Each of those objects can have different values for their instance variables (and properties), and they all have their own distinct life time from a memory-management standpoint. Calling the pair of methods alloc and init is one very common way to make a new instance of a class, that has its own lifetime and instance variables.
Finally, I'd like to suggest that you read and follow Apple's Cocoa style guide as your choice of names for methods and classes has caused confusion among your fellow developers. If you start to apply that you will find communication with others to go smoother and your problems easier to understand.

All you need is
- (void)toggleChromeDisplay
{
isChromeHidden_ = !isChromeHidden_;
}
(based on your edit)

toggleChrome: sets the isChromeHidden_ variable, it does not toggle it. To toggle you would write:
- (void)toggleChrome
{
isChromeHidden_ = !isChromeHidden_;
//Find chrome value
NSLog(isChromeHidden_ ? #"YES" : #"NO");
}
!isChromeHidden_ is the opposite value of isChromeHidden_.

I copied your exact code into my project and it is switching between YES and NO as expected. This tells me that your code that you have posted is in fact correct and you are either calling it incorrectly or you are setting the variable somewhere else as well.

Related

delegate method not getting called

I have looked at all the other questions with the same problem but I cannot seem to get my heard around it. I am pretty sure I have done everything correctly as this is not my first time using delegates.
//PDFView.h
#class PDFView;
#protocol PDFViewDelegate <NSObject>
-(void)trialwithPOints:(PDFView*)pdfview;
#end
#interface PDFView : UIView
#property (nonatomic, weak) id <PDFViewDelegate> delegate;
In the implementation file i am trying to call the delegate method from touchesMoved delegate of view
//PDFView.m
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.delegate trialwithPOints:self];
}
The class where the delegate method is implemented
//points.h
#import "PDFView.h"
#interface points : NSObject <PDFViewDelegate>
//points.m
//this is where the delegate is set
- (id)init
{
if ((self = [super init]))
{
pdfView = [[PDFView alloc]init];
pdfView.delegate = self;
}
return self;
}
-(void)trialwithPOints:(PDFView *)pdf
{
NSLog(#"THE DELEGATE METHOD CALLED TO PASS THE POINTS TO THE CLIENT");
}
So this is how i have written my delegate and somehow the delegate is nil and the delegate method is never called.
At the moment I am not doing anything with the delegate, I just want to see it working.
Any advices on this would be highly appreciated.
I think it is because you did not hold the reference to the instance of the delegate, and it got released because it is declared weak. You might be doing this:
pdfView.delegate = [[points alloc] init];
which you should fix to something like:
_points = [[points alloc] init];
pdfView.delegate = _points;
where _points is instance variable.

Trouble detecting a touch on a nested custom sprite layer

I have a layer, HelloWorldLayer below, where touch works anywhere, but I'd like it to work only when touching a sprite in the layer -- turtle below.
If I try to add self.isTouchEnabled = YES; onto the CCTurtle layer it says
property isTouchEnabled not found on object type CCTurtle
my output reads as follows
2013-01-08 20:30:14.767 FlashToCocosARC[6746:d503] cocos2d: deallocing
2013-01-08 20:30:15.245 FlashToCocosARC[6746:d503] playing walk animation2
Here's my HelloWorldLayer code:
#import "HelloWorldLayer.h"
#import "CCTurtle.h"
#implementation HelloWorldLayer
+(CCScene *) scene
{
CCScene *scene = [CCScene node];
HelloWorldLayer *layer = [HelloWorldLayer node];
[scene addChild: layer];
return scene;
}
-(id) init
{
if( (self=[super init])) {
turtle= [[CCTurtle alloc] init];
[turtle setPosition:ccp(300, 100)];
[self addChild:turtle];
///addChild:child z:z tag:aTag;
self.isTouchEnabled = YES;
turtle. tag=4;
//
}
return self;
}
//- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//{
// // Processing all touches for multi-touch support
// UITouch *touch = [touches anyObject];
// if ([[touch view] isKindOfClass:[turtle class]]) {
// NSLog(#"[touch view].tag = %d", [touch view].tag);
// [self toggleTurtle];
// }
//}
-(BOOL)containsTouch:(UITouch *)touch {
CGRect r=[turtle textureRect];
CGPoint p=[turtle convertTouchToNodeSpace:touch];
return CGRectContainsPoint(r, p );
}
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//////GENERAL TOUCH SCREEN
for (UITouch *touch in touches) {
CGPoint touchLocation = [touch locationInView:[touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
[self toggleTurtle];
/////
}
}
-(void) toggleTurtle
{
NSLog(#"playing walk animation2");
[turtle playAnimation:#"walk_in" loop:NO wait:YES];
}
#end
//hello world.h
#import "cocos2d.h"
#import "CCTurtle.h"
#interface HelloWorldLayer : CCLayer
{
CCTurtle *turtle;
}
+(CCScene *) scene;
#end
//CCturtle
#import <Foundation/Foundation.h>
#import "FTCCharacter.h"
#interface CCTurtle : FTCCharacter <FTCCharacterDelegate, CCTargetedTouchDelegate>
{
}
#end
I'm using Cocos2D cocos2d v1.0.1 (arch enabled), and am testing on ipad 4.3 simulator.
with thanks Natalie
ive tried to put the touches directly into ccturtle.m so it can handle its own touches using CCTargetedTouchDelegate as above but using
CCturtle/// I changed files to this trying a different way to find the touched area...
- (CGRect)rect
{
CGSize s = [self.texture contentSize];
return CGRectMake(-s.width / 2, -s.height / 2, s.width, s.height);
}
-(BOOL) didTouch: (UITouch*)touch {
return CGRectContainsPoint(self.rect, [self convertTouchToNodeSpaceAR:touch]);
//return CGRectContainsPoint( [self rect], [self convertTouchToNodeSpaceAR: touch] );
}
-(BOOL) ccTouchBegan:(UITouch*)touch withEvent: (UIEvent*)event {
NSLog(#"attempting touch.");
if([self didTouch: touch]) {
return [self tsTouchBegan:touch withEvent: event];
}
return NO;
}
but still wont compile as still returns the error "Property 'is TouchEnabled' not found on object type 'CCTurtle*'
am really not sure what i can do to get it to run now... and really need to get this working (i suppose i could make invisible buttons, but it would be nicer to be able to find the ccturtle properly and to understand what im doing wrong... hope someone can help
First of all, I cannot see anywhere calling of containsTouch: method. And here are several advices:
Use boundingBox instead of textureRect to get local rect of your node (your turtle, in this case). Or just replace containsTouch: method to your turtle class to incapsulate this. It can be helpful, for example, if you want to make touch area of your turtle bigger/smaller. You will just need to change one little method in your turtle class.
In your ccTouchesBegan:withEvent: method just check for every turtle if it is hit by this touch. Then, for example, you can create dictionary, with touch as the key and array of corresponding turtles as the value. Then you just need to update all turtles positions for moved touch in your ccTouchesMoved:withEvent: method and remove this array of turtles from the dictionary in ccTouchesEnded:withEvent: and ccTouchCancelled:withEvent: method.
If you want your CCTurtle object to accept targeted touches, you can do it by specifying that it conforms to the CCTargetedTouchDelegate protocol. In your CCTurtle #interface, you declare it like so:
#interface CCTurtle : CCNode <CCTargetedTouchDelegate>
Then in the implementation, you tell it to accept touches and implement the ccTouch methods:
#implementation CCTurtle
-(id) init {
.
.
[[CCDirector sharedDirector].touchDispatcher addTargetedDelegate:self priority:1 swallowsTouches:YES];
return self;
}
-(void) onExit {
[[CCDirector sharedDirector].touchDispatcher removeDelegate:self];
}
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint location = [[CCDirector sharedDirector] convertToGL:[touch locationInView:[touch view]]];
if (CGRectContainsPoint([self boundingBox], location] {
// some code here
}
}
-(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event { // code here }
-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event { // code here}
-(void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event { // code here}
Thanks to Prototypical the issue was solved,
Although the CCTurtle was a layer with a type of sprite on it was nested sprites
which meant that cocos2d had problems creating the correct bounding box for my
"contains touch method"
so with a bit of magic he combined his "get full bounding box" method to the contains touch method to account for the children of the sprite, and the code now relies on collision detection to process the touch.
currently im happily working away on some nice icons for him in return
but wanted to say thank-you to all that helped, and hope that this method comes in handy for anyone with the same problem!

How to detect when no fingers are on the screen?

I need some help with the touchesEnded function. I want to start a NSTimer when there are no fingers on the screen using the touchesEnded function. Is this possible?. Currently I have a touchesBegan function working :-).
Here's my code:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSUInteger numTaps = [[touches anyObject] tapCount];
if (numTaps >= 2)
{
self.label.text = [NSString stringWithFormat:#"%d", numTaps];
self.label2.text = #"+1";
[self.button setHidden:YES];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
}
- (void)showButton
{
[self.button setHidden:NO];
}
It's tricky. You don't get an event that tells you that all fingers are up; each touchesEnded only tells you that this finger is up. So you have to keep track of touches yourself. The usual technique is to store touches in a mutable set as they arrive. But you can't store the touches themselves, so you have to store an identifier instead.
Start by putting a category on UITouch, to derive this unique identifier:
#interface UITouch (additions)
- (NSString*) uid;
#end
#implementation UITouch (additions)
- (NSString*) uid {
return [NSString stringWithFormat: #"%p", self];
}
#end
Now we must maintain our mutable set throughout the period while we have touches, creating it on our first touch and destroying it when our last touch is gone. I'm presuming you have an NSMutableSet instance variable / property. Here is pseudo-code:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// create mutable set if it doesn't exist
// then add each touch's uid to the set with addObject:
// and then go on and do whatever else you want to do
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
// remove uid of *every* touch that has ended from our mutable set
// if *all* touches are gone, nilify the set
// now you know that all fingers are up
}
To create an idle timer, the simplest way is to create a custom subclass of UIApplication, and override sendEvent: - here, call super, and reset your timer. This will cover all touches for you. Every touch your app receives goes through this method.
To use the custom application subclass you need to modify the call in main.m to UIApplicationMain(), inserting your custom class name.

Implementing UITapGestureRecognizer directly into UIView instead of ViewController does not work

As explained in this SO-answer I am trying to implement UITapGestureRecognizer in a subclass of UIIMageView. My approach can be found below.
An instance of MenuButtonImageView is a subview of homeScreenViewController.view.
I implemented touchesBegan:withEvent:, touchesMoved:withEvent: and touchesEnded:withEvent: too and do work fine.
Problem: Somehow handleSingleFingeredTap: is never called. What could be the problem with this?
#interface MenuButtonImageView : UIImageView
#property (nonatomic, weak) IBOutlet HomescreenViewController *homeScreenViewController;
#property (nonatomic, readwrite) Visibility visibility;
- (void)handleSingleFingeredTap:(UITapGestureRecognizer *)recognizer;
#end
#implementation MenuButtonImageView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.visibility = HIDDEN;
self.userInteractionEnabled = YES;
UITapGestureRecognizer * singleFingeredTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleSingleFingeredTap:)];
singleFingeredTap.numberOfTapsRequired = 1;
[self addGestureRecognizer:singleFingeredTap];
}
return self;
}
- (void)handleSingleFingeredTap:(UITapGestureRecognizer *)recognizer {
NSLog(#"handleTap was called"); // This method is not called!
[self toggleMainMenu];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { ... }
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { ... }
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { ... }
#end
You add the recognizer in initWithFrame method. Check if your view is initialized this way. It may be created with another constructor like initWithCoder, and then your code is not executed. Put a breakpoint inside initWithFrame method to find out.
You can put the code in a separate method and call it from both constructors. It depends on how you use it. The initWithFrame is used quite common when you create a view from code.

UIImageview and TouchesEnded Event

Im trying to write a simple program that takes 5 images and allows you to drag them from the bottom of the screen and snap them on to 5 other images on the top in any order you like. I have subclassed the UIImageView with a new class and added the touches began, touches moved and touches ended. Then on my main viewcontroller I place the images and set their class to be the new subclass I created. The movement works great in fact I am NSLogging the coordinates in the custom class.
Problem is I'm trying to figure out how to get that CGpoint info from the touches end out of the custom class and get it to call a function in my main view controller that has the image objects so i can test whether or not the image is over another image. and move it to be centered on the image its over (snap onto it).
here is the code in my custom class m file. MY view controller is basically empty with a xib file with 10 image views 5 of which are set to this class and 5 are normal image views..
#import "MoveImage.h"
CGPoint EndPoint;
#implementation MoveImage
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
startPoint = [[touches anyObject] locationInView:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint newPoint = [[touches anyObject] locationInView:self.superview];
newPoint.x -= startPoint.x;
newPoint.y -= startPoint.y;
CGRect frm = [self frame];
frm.origin = newPoint;
[self setFrame:frm];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *end = [[event allTouches] anyObject];
EndPoint = [end locationInView:self];
NSLog(#"end ponts x : %f y : %f", EndPoint.x, EndPoint.y);
}
#end
You could write a MoveImageDelegate protocol which your app controller would then implement. This protocol would have methods that your MoveImage class can call to get its information.
In your header file ( if you don't know how to write a protocol )
#protocol MoveImageDelegate <TypeOfObjectsThatCanImplementIt> // usually NSObject
// methods
#end
then you can declare an instance variable of type id, but still have the compiler recognize that that variable responds to your delegate selectors ( so you can code without those annoying warnings ).
Something like:
#interface MoveImage : UIImageView
{
id <MoveImageDelegate> _delegate;
}
#property (assign) id <MoveImageDelegate> delegate;
Lastly:
#implementation MoveImage
#synthesize delegate = _delegate;
And your delegate is complete.