How to Create Dynamic Value Which Can use Entire App - ios

Basiclly, I have a button which created value according to finish some math process like +, - , /, *. Question is when I get some value, I needed to use that value again when I press button second time. Let me explain Basicly,
When I clicked button process like,
int examplea = [txt_example.text intValue];
int exB = 5000;
int exC = exB - examplea;
This is the first time I push the button, my lastest value is exC When I input text field another value and clicked it same process will start but one difference:
int examplea = [txt_example.text intValue];
int exB = exC;
int exC ( this new value which will be calculated ) = exB - examplea;
How can I create process like this?

Something like this
in the .h file
#interface MyCalculator : NSObject
- (int) doCalculation;
#property (assign, nonatomic) int exB;
#end
in the .m file
#implementation MyCalculator
- (id) init
{
self = [super init];
if (self)
{
_exB = 5000;
}
return self;
}
- (int) doCalculation
{
int examplea = [txt_example.text intValue];
int exC = self.exB - examplea;
self.exB = exC;
return exC;
}
#end
....
MyCalculator* myCalculator = [[MyCalculator alloc] init];
...
[myCalculator doCalculation];
This isn't the full solution as there are several questions about what your code will do, but it will illustrate the principle of how to do it.
The last line is what gets called when the button is pressed.
I don't know where txt_example.text is coming from, but it might be better if that is passed to doCalculation as a parameter.

Related

Random number that doesn't repeat twice in a row [duplicate]

This question already has answers here:
Non repeating random numbers in Objective-C
(6 answers)
Closed 7 years ago.
I'm pretty new to coding, I've been looking for similar questions but none fits my needs. I'm working in a dice rolling app, and I need a a random number generator to "roll" the dice. arc4random seems perfect, but the problems that I can't have the same face occurring twice in a row. I have a method firing when I press the button with a timer
- (IBAction)dieRoll:(id)sender {
self.currentFace = 1;
_timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:#selector(roll) userInfo:nil repeats:YES];;
}
but I have to implement the 'roll' method where I get a random number different from the one already selected (the property self.currentFace).
any clue?
this is how your implementation could look like:
#interface ViewController ()
#property (assign, nonatomic) NSInteger currentFace;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.currentFace = -1;
}
- (IBAction)diceRoll:(id)sender {
NSInteger newFace = -1;
do {
newFace = arc4random_uniform(6) + 1;
} while (newFace == self.currentFace);
self.currentFace = newFace;
}
#end
A simple solution would be to just remember the last rolled number and roll the dice until you get a different one. Pretty simple and you can keep arc4random.
An example:
- (NSUInteger)rollDiceWithLastFaceNumber:(NSUInteger)lastFaceNumber
{
NSUInteger currentFaceNumber;
do {
currentFaceNumber = (arc4random_uniform(6) + 1);
} while (currentFaceNumber == lastFaceNumber);
return currentFaceNumber;
}
and how to use it:
[self rollDiceWithLastFaceNumber:3];
This solution avoids an unknown number of iterations until you get your result.
- (void)roll {
NSUInteger next = [self nextFaceWithPreviousFace:self.currentFace];
NSLog(#"%lu", next);
self.currentFace = next;
}
- (NSUInteger)nextFaceWithPreviousFace:(NSUInteger)previous {
NSMutableArray *candidates = [NSMutableArray arrayWithObjects:#1, #2, #3, #4, #5, #6, nil];
[candidates removeObject:#(previous)];
NSUInteger index = arc4random_uniform((unsigned)candidates.count);
return [candidates[index] unsignedIntegerValue];
}

Can't change "int" in Objective C

I have had a very weird experience with Objective C and xCode these last couple of days. I'm now turning to you guys for some quick help.
I'm simply trying to set up and int, call in damage(the amount of damage this object is supposed to do) and increase it if a void function is called.
-(void) increaseDagage{
damage = damage + 100;
NSLog(#"%f", damage);
}
I have tried setting the int damage up as a int and also as
#property (nonatomic, assign) float damage;
The problem is that when I print "damage" it hasn't increased...
I also have a function that returns the amount of damage this object does and it returns the wrong value.
I can't figure out why this isn't doing what I want...
I also have an int called health, which is basically the same thing and works fine.
Here's the full class if you want to see that too,
//
// Character.m
// TD
//
// Created by Victor Appelgren on 2014-12-23.
// Copyright (c) 2014 Victor Appelgren. All rights reserved.
//
#import "Character.h"
#import "constants.h"
#import "Level.h"
#import "GameViewController.h"
#interface Character (){
SKSpriteNode *character;
float health;
float maxHealth;
Level *level;
GameViewController *gVC;
BOOL dead;
int damage;
}
//#property (nonatomic, assign) float damage;
#end
#implementation Character
-(id) init {
if (self = [super init]){
damage = 100;
dead = NO;
// Load health
maxHealth = 200;
health = 200.0;
self.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:character.frame.size.width / 2];
[self addChild:character];
}
return self;
}
-(void) doDamageType:(int)type{ // here a type is passed in to tell how much damage is being done.
if (type == 1){
health = health - 20;
} else if (type == 2){
health = health - 40;
}
if (health <= 0){
[self removeFromParent];
dead = YES;
}
}
-(void) increaseDagage{
damage = damage + 100.0;
// NSLog(#"%f", _damage);
}
-(int) returnDamage{
return damage;
}
-(BOOL) returnDead{
return dead;
}
-(float) returnHealth{
return health;
}
-(float) returnMaxHealth{
return maxHealth;
}
#end
Here's the output I'm getting,
2015-02-22 01:28:27.722 TD[279:43180] 200.000000
2015-02-22 01:28:30.327 TD[279:43180] 200
2015-02-22 01:28:30.496 TD[279:43180] 200
2015-02-22 01:28:30.644 TD[279:43180] 200
2015-02-22 01:28:30.809 TD[279:43180] 200
first is initial value and the rest is from when the function is being called
What is wrong....
I might be missing something here but can't seem to find the problem
Thanks for the help
The problem is that you've created two different damage variables -- one in your .h and another in your .m. The one in your .h is public and accessible from your .m using self.damage. The one you've declared in your .m is private and accessible simply using damage. So the problem here is that you're accessing the public version of your damage from the other class, but you're actually manipulating the private version within your class.
So I'd recommend changing the following methods and property declarations of your .m as follows:
// ***Remove the private declaration of damage***
#interface Character (){
SKSpriteNode *character;
float health;
float maxHealth;
Level *level;
GameViewController *gVC;
BOOL dead;
}
#end
#implementation Character
// ***And add "self." before each instance of damage***
-(id) init {
if (self = [super init]){
self.damage = 100;
dead = NO;
// Load health
maxHealth = 200;
health = 200.0;
self.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:character.frame.size.width / 2];
[self addChild:character];
}
return self;
}
-(void) increaseDagage{
self.damage = self.damage + 100.0;
// NSLog(#"%f", self.damage);
}
-(int) returnDamage{
return self.damage;
}
#end
You have a spelling error in your method name : increaseDagage
I am guessing this should be increaseDamage
You also seem to be creating your own setters and getters. I would read up on the usage of properties.
Several things jump out:
Your method is called increaseDagage. Do you get any error message in Xcode's console when you call it?
You are not telling us whether you are getting any error or warning messages from the code. You should be getting some.
You keep talking about ints, but the log statement and property you define are floats.
You are not #synthesizeing your float damage property. So that means that it will create its own _damage instance variable to store the value and not use your damage instance variable (which would be the wrong type anyway).
You are logging _damage, not damage.
In short, the code, as written, mixes up two completely different things.

Why can I not assign a value to my ivar?

it has been a while since I did anything in ObjC. I am sure the mistake is trivial but I can't seem to find it.
I created a class called Game with the following .h file:
#import <Foundation/Foundation.h>
#interface FSGame : NSObject
#property NSInteger numberOfGames;
#end
In the implementation file of one of my view controllers, a method then uses the user's selection from a segm. control to determine the number of games:
FSGame *game;
// Number of Games
NSInteger index = _segCtrlNumberGames.selectedSegmentIndex;
if (index == 0) {
game.numberOfGames = 1;
} else if (index == 1) {
game.numberOfGames = 3;
} else {
game.numberOfGames = 5;
}
NSLog(#"Games: %i; index: %i", game.numberOfGames, index);
The NSLog returns: Games: 0; index: 2
I have the same issue with two other classes I created. I grab text from a UITextField and the NSLog displays it correctly so I know I am actually able to get the user's input - it just wont store it as an ivar.
This must be something really obvious. Any pointers?
You create the Game object:
Game *game;
But you should create NSGame instead and you need to allocate and initialise it as well:
FSGame *game = [[FSGame alloc] init];

Trouble understanding static class in iOS

I am following the Big Nerd Ranch book on iOS programming.
There is a sample of a static class:
#import <Foundation/Foundation.h>
#interface BNRItemStore : NSObject
+ (BNRItemStore *) sharedStore;
#end
I have a problem undrstanding the bit below with question mark in the comments.
If I try to alloc this class, the overriden method will bring me to sharedStore, which in turn sets the static pointer sharedStore to nil. The conditional after will hit the first time because the pointer doesn't exist.
The idea is that the second time I am in the same place, it would not alloc a new instance and get the existing instance instead. However with static BNRItemStore *sharedStore = nil; I am setting the pointer to nil and destroy it, isn't it? Hence every time I am creating unintentionally a new instance, no?
#import "BNRItemStore.h"
#implementation BNRItemStore
+ (BNRItemStore*) sharedStore
{
static BNRItemStore *sharedStore = nil; // ???
if (!sharedStore) {
sharedStore = [[super allocWithZone:nil] init];
}
return sharedStore;
}
+(id)allocWithZone:(NSZone *)zone
{
return [self sharedStore];
}
#end
However with static BNRItemStore *sharedStore = nil; I am setting the pointer to nil and destroy it, isn't it?
No, you do not set it to nil: the expression in the static initializer is computed only once; the second time around the initialization has no effect. This looks very confusing, but this is the way the function-static facility works in C (and by extension, in Objective-C).
Try this as an example:
int next() {
static int current = 123;
return current++;
}
int main(int argc, char *argv[]) {
for (int i = 0 ; i != 10 ; i++) {
NSLog(#"%d", next());
}
return 0;
}
This would produce a sequence of increasing numbers starting at 123, even though the code makes it appear as if current is assigned 123 every time that you go through the function.

How to connect Test application in objective c

I am a beginner of objective c. I created unit test application. How am I call test method?
Bellow given my sample code.
my project ::
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
int a=25;
int b=25;
MyUnitTestTests *myValue;
if ([myValue respondsToSelector:#selector(testExample:testExample:)])
{
int c = [myValue testExample:25 testExample:10];
NSLog(#"value %i",c);
}
[super viewDidLoad];
}
Test method ::
- (int)testExample:(int )a testExample:(int )b
{
int c= a+b;
return c;
}
is there any error ??
I tried lot of time to do this simple test. but output was (value 0)
Your output is not correct
NSLog(#"value %d", c);
Thus, without %i and with %d it should be correct.
And there is another bug: the instance myValue was not initialized.
MyUnitTestTests *myValue = [[MyUnitTestTests alloc] init];
Instead of typing int c = [myValue testExample:25 testExample:10];
Just type [self testExample:25 testExample:10];
And print the log statement in your test method.

Resources