"unused variable" - objective-c

#implementation demoScene{
-(void) initializeScene {
moon *_moon=[[moon alloc]init];
}
-(void) updateBeforeTransform: (CC3NodeUpdatingVisitor*) visitor {
deltaTime =deltaTime+visitor.deltaTime;
NSLog(#"delta time=%0.12f",deltaTime);
[_moon print:deltaTime/100000];
}
#end
Here is my problem.
I want to create an object from moon class in initializeScene method and I want to send message to that object in updateBeforeTransform method.
When I type the code like this, I can not send message to _moon object and get "unused variable" warning message.
I know the object is out of scope but if i need to send message from updateBeforeTransform method. And updateBeforeTransform method is called like 60 time in a second. So I did not want to create an object 60 times in a seconds.
Any suggestion would be appreciated.

You need an instance variable instead of creating a new variable in the initializeScene method:
#implementation demoScene {
moon *_moon; // You may already have this in the .h file - just have it in 1 place.
}
- (void)initializeScene {
_moon = [[moon alloc] init]; // assign to ivar
}
- (void)updateBeforeTransform:(CC3NodeUpdatingVisitor*) visitor {
deltaTime = deltaTime + visitor.deltaTime;
NSLog(#"delta time=%0.12f", deltaTime);
[_moon print:deltaTime / 100000];
}
#end
Side note - Class names should begin with uppercase letters. Variables and method names begin with lowercase letters.

Related

Cannot keep track of the value of my property in Objective-c

I have a problem with one property in one class. I am coding with iOS 6.1 if it makes any difference.
The class is UIViewController and the property is the declared in the header file like so:
// Keeps track of time in seconds
#property (nonatomic, strong) NSNumber *timeInSeconds;
In my implementation file I use the property during 3 occasions:
one is to add time with the method - (void)addTime
one is to subtract time with the method - (void)subtractTime
Those two methods use the property like so:
- (void)addTime
{
CGFloat timeFloat = [self.timeInSeconds floatValue];
// Here I set the value of the property timeInSeconds, but I can't access that value later on in the code!
self.timeInSeconds = [NSNumber numberWithFloat:timeFloat +5];
NSLog(#"Total Time:%#", self.timeInSeconds);
}
The two methods addTime and subtractTime do what they are supposed to do, and they keep a good track of the property timeInSeconds value as I add then subtract then add...
The problem is when I call in the same implementation file the third method which is:
- (void)updateLabelTime
{
self.label.attributedText = [[NSAttributedString alloc]initWithString:[self.timeInSeconds stringValue]];
[self.label setNeedsDisplay];
[NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:#selector(updateLabelTime) userInfo:nil repeats:YES];
}
I also tried to create a the NSAttributedString with stringWithFormat instead of initWithString but the problem persists which is that instead of returning the value of the property timeInSeconds which i previously set using addTime and subtractTime, it calls the getter which creates a new instance of timeInSeconds since in my getter I have lazy instantiation.
I tried to not write the getter/setter for the property (since I am using iOS 6.1) but it makes no difference.
If I just set the label to some random string, it would work. The problem is that if I know the value of timeInSeconds is 55, it would still create a new _timeInSeconds.
I tried my best with my English since I am French, please don't answer if the question was already asked by a beginner iOS developer and just redirect me. I couldn't find an answer though, thanks!
EDIT: Here is the custom getter
- (float)timeInSeconds
{
if (!_timeInSeconds) {
_timeInSeconds = 0;
}
return _timeInSeconds;
}
SECOND EDIT:
The stupid beginner mistake that I made was that addTime and subtractTime are actually implementing a protocol and they set the property which "lives" in another class which is why I could not access it! That other class that needs the protocol was creating a new instance of the class where addTime and subtractTime is written.
What needs to be done is to set the controller as the delegate for the protocol. I did this in the viewDidLoad method with something like:
self.view.delegate = self;
Thanks for all the help.
In your header file, declare this property:
#property (assign) float timeInSeconds;
In the implementation file:
#synthesize timeInSeconds = _timeInSeconds;
- (void)viewDidLoad
{
[super viewDidLoad];
_timeInSeconds = 0.0f;
}
- (void)addTime
{
_timeInSeconds += 5.0f;
}
This should initialize timeInSeconds to zero and then increment its value by 5 each time you call addTime. To use its value in the label:
- (void)updateLabelTime
{
self.label.text = [NSString stringWithFormat:#"%f", _timeInSeconds];
}
In your custom getter you are assigning a scalar value to an object property. In fact assigning zero to an object property is the equivalent of setting the object to nil.
What you need to do is this:
- (float)timeInSeconds
{
if (!_timeInSeconds) {
_timeInSeconds = [NSNumber numberWithFloat:0.0f];
// or alternatively with the latest version of objective c
// you can more simply use:
// _timeInSeconds = #(0.0f);
}
return _timeInSeconds;
}

Objective-C blocks usage

I have been looking around online, doing research into how to use blocks. I have also decided to set up a basic example to try and understand the way in which they work.
Essentially what I want to do is have a 'block variable' (no sure if thats the correct term) in which I can store a block of code. I then want to be able to set the code in this block at pointX (methodA or methodB) in my code, then run the block of code at pointY (methodX).
So to be specific, my question is 3-fold
Using the example below is the setup / usage of blocks correct and valid?
In methodX how do I execute the code inside the block (self.completionBlock)?
When creating the block in methodA and methodB will the code be called there and then? If so how can I stop this from happening (all I want to do is set up the code in the block to be called later)?
I may have completely misunderstood how blocks are used, apologies if this is the case, however I'm relatively new to Objective-C and I'm trying to learn.
Here is my code so far:
.h
typedef void (^ CompletionBlock)();
#interface TestClass : NSObject
{
CompletionBlock completionBlock;
NSString *stringOfText;
NSString *otherStringOfText;
}
#property(nonatomic, copy)CompletionBlock completionBlock;
#property(nonatomic, retain)NSString *stringOfText;
#property(nonatomic, retain)NSString *otherStringOfText;
- (void)methodA:(NSString *)myText;
- (void)methodB:(NSString *)myText and:(NSString *)myOtherText;
- (void)methodX;
#end
.m
- (void)methodA:(NSString *)myText;
{
if ([self.stringOfText isEqualToString:#""])
{
// Set the variable to be used by the completion block
self.stringOfText = #"I visited methodA"; // normally make use of myText
// Create the completion block
__block TestClass *blocksafeSelf = self;
self.completionBlock = ^()
{
[blocksafeSelf methodA:blocksafeSelf.stringOfText];
blocksafeSelf.stringOfText = nil;
};
}
else
{
// Do some other stuff with self.stringOfText
}
}
- (void)methodB:(NSString *)myText and:(NSString *)myOtherText;
{
if ([self.stringOfText isEqualToString:#""] || [self.otherStringOfText isEqualToString:#""])
{
// Set the variable to be used by the completion block
self.stringOfText = #"I visited methodB"; // normally make use of myText
self.otherStringOfText = #"I also visited methodB"; // normally make use of myOtherText
// Create the completion block
__block TestClass *blocksafeSelf = self;
self.completionBlock = ^()
{
[blocksafeSelf methodB:blocksafeSelf.stringOfText and:blocksafeSelf.otherStringOfText];
blocksafeSelf.stringOfText = nil;
blocksafeSelf.otherStringOfText = nil;
};
}
else
{
// Do some other stuff with self.stringOfText and self.otherStringOfText
}
}
- (void)methodX
{
// At this point run the block of code in self.completionBlock...how?!
}
In my example either methodA or methodB will be called first. Then some time later (perhaps from a different class) methodX will be called (only ever after methodA or methodB have been called).
It's worth noting that the methods methodA, methodB and methodX are all in a singleton class.
NOTE: This is just a dummy example to try and understand the workings of blocks, I'm fully aware there are other ways to achieve the same result.
Here's the code, just to be clear:
- (void)methodX
{
if(self.completionBlock)
self.completionBlock();
}
I think you want to do self.completionBlock(); in methodX.

Variable out of IBAction

I have problem that im trying to get solve for like week.
My goal is to get variable out of my IBAction, to use for example in -(void)viewDidLoad..
But as far as I am now I can use my variable only in my IBAction..
- (IBAction) changeLat:(NSNumber *)str {
longi = str;
double lop = longi.doubleValue;
NSLog(#"%f",lop);
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog (#"%#",lop);
}
It NSLog shows everything fine in action, but in view did load it doesn't even recorganize it.
If you create a variable inside of -IBAction, the scope of that variable is only that method, so you cannot access to that variable outside it.
If you want your variable to be global to your class, you have to create it in the declaration of your class, like this:
#interface MainViewController () {
#private
double lop;
}
Put this at the beginning of your .m file, and then lop would be accesible in all your class.
You can read more about the scope of the variables here:
http://www.techotopia.com/index.php/Objective-C_Variable_Scope_and_Storage_Class
Actually, IBAction is converted to void by the preprocessor. It's used by Interface Builder as a label that identifies this method as an action able to be related from an IB Object.
There's no way (AFAIK) to use two return types in a function (for example `(IBAction double)´, equivalent to ´(void double)´), but a good practice could be something like this:
- (IBAction)changeLatAction:(id)sender {
NSNumber *str = <get the NSNumber from a valid place>;
[self changeLat:str];
}
- (double) changeLat:(NSNumber *)str {
longi = str;
double lop = longi.doubleValue;
NSLog(#"%f",lop);
return ????;
}
Your first declaration of changeLat seems to be wrong, because as a first parameter you'll always get the "sender" or "caller" object, related from IB (when called from an action, of course), so, you need to get the str value from a valid place.
Cheers.

how to call a function of a same class from other functions of the same class-Objective C

But i'm getting errors when declaring like this.
#implementation data
-(void)SwapEndian:(uint8_t*)pData withBOOLValue:(bool)bIsAlreadyLittleEndian
{
data* datas = [data alloc];
[datas swapEndians:(uint8_t)&pData[nIndex] withSize:(sizeof(uint32_t));
}
-(void)swapEndians:(uint8_t*)pData withnByteSize:(int const)nByteSize
{
NSLog(#"swapEndians!!");
}
#end
How to call a function from other function inside the same class?
You can use self keyword to achieve this.
[self yourFunctionName];
First things first:
data* datas = [data alloc]; // Where is your init? Don't use un-initialized objects!
[datas swapEndians:(uint8_t)&pData[nIndex] withSize:(sizeof(uint32_t));
Second thing:
If the method you are trying to call is the second one from you code, you have a typo in the selector!
That line should read:
[datas swapEndians:&pData[nIndex] withnByteSize:sizeof(uint32_t)];
Third thing:
You send messages to yourself by using self.
First of all class name should start with capital letter, here is I think you are tying to do
#implementation Data //changed it just naming convention
-(void)swapEndian:(uint8_t*)pData withBOOLValue:(bool)bIsAlreadyLittleEndian
{
[self swapEndians:(uint8_t)&pData[nIndex] withSize:(sizeof(uint32_t));
}
-(void)swapEndians:(uint8_t*)pData withnByteSize:(int const)nByteSize
{
NSLog(#"swapEndians!!");
}
#end

Count the number of times a method is called in Cocoa-Touch?

I have a small app that uses cocos2d to run through four "levels" of a game in which each level is exactly the same thing. After the fourth level is run, I want to display an end game scene. The only way I have been able to handle this is by making four methods, one for each level. Gross.
I have run into this situation several times using both cocos2d and only the basic Cocoa framework. So is it possible for me to count how many times a method is called?
Can you just increment an instance variable integer every time your method is called?
I couldn't format the code in a comment, so to expound more:
In your header file, add an integer as a instance variable:
#interface MyObject : NSObject {
UIInteger myCounter;
}
And then in your method, increment it:
#implementation MyObject
- (void)myMethod {
myCounter++;
//Do other method stuff here
if (myCounter>3){
[self showEndGameScene];
}
}
#end
I don't know if your way is the best way to do it, or if mine is, but like Nathaniel said, you would simply define an integer to hold the count in your #interface:
#interface MyClass : NSObject {
int callCount;
}
Then the method can increment this by doing:
- (void) theLevelMethod {
callCount++;
// some code
}
Make sure you initialize the callCount variable to 0 though, in your constructor or the equivalent of viewDidLoad. Then in the code that checks the count you can check:
if (callCount == 4) {
// do something, I guess end scene
}
Then again, I guess you can simply do something like this:
for (int i = 0; i < 4; i++) {
[self theLevelMethod];
}
[self theEndScene];
I don't know how your game logic works, but I guess that would work.
Sorry if I misunderstood your question.