Objective-C and integers outside methods - ios

I have a question regarding integers outside of methods in Objective-C/Xcode. I'm trying to create a simple guessing game, however my randomizer randomize number every time when the method is called, here is the code snipped:
- (IBAction)guessButton:(id)sender {
int tempUserGuess = [self.textField.text integerValue];
int randomNumber = (arc4random() % 11);
if(tempUserGuess == randomNumber){
self.guessAns.text = #"you won!";
}
if (tempUserGuess < randomNumber){
self.guessAns.text = #"no! too low!";
}
if (tempUserGuess > randomNumber){
self.guessAns.text = #"no! too high!";
}
}
The reason why I'm trying to put an int outside of the method is of that once randomized integer should not be randomized every single time (of course). By the way, everything works fine, the app compiles and works but every single time when I hit return, it randomizes the number.
I know how to do this in Java, but Objective-C seems to be more complex.

Your guessButton method is probably a member of some class. You need to add property to that class holding that randomized number.

You only have to create/store a random number once per game play. There is no need to call the randomize method each time the guess button is pressed. The guessButton method is basically like an ActionListener in java. Each time the button is pressed, whatever's inside the curly braces will be executed. If you add a play again button to the game, then you might want to call the randomize method inside of it's action method.

if(tempUserGuess == num){
self.guessAns.text = #"you won!";
}
This will be a good way because it will be using less memory in the sytem when trying to divert the random number. Good work

Okay, I got it.
Here is the answer:
in ViewController.h I had to include:
NSInteger num;
and then in ViewController.m a method that simply returns a number:
-(int)giveRandom {
int randomNumber = (arc4random() % 10);
return randomNumber;
}
And then refer to 'num' in the method with if statements such as:
...
if(tempUserGuess == num){
self.guessAns.text = #"you won!";
}
...
For some reason it returns 0, but I will try to solve it.
Thanks!

Related

Randomly Selecting In EarlGrey

I was writing pretty complicated UI tests using XCTest, and recently switched to EarlGrey, because it's so much faster and way more reliable - Tests aren't randomly failing on a build server, and the test suite could take up to a half hour to run!
One thing that I haven't been able to do in EarlGrey, that I could do in XCTest, was randomly select an element.
For example, on a calendar collectionView, I could query for all collectionViewCells with 'identifier' using an NSPredicate, and then randomly select a day using [XCUIElementQuery count] to get an index, and then tap.
For now, I'm going to hard code it, but I would love to randomize date selection so that I don't have to rewrite tests if we change app code.
Please let me know if I can elaborate, looking forward to solving this!
Step 1 write a matcher that can count elements matching a given matcher using GREYElementMatcherBlock:
- (NSUInteger)elementCountMatchingMatcher:(id<GREYMatcher>)matcher {
__block NSUInteger count = 0;
GREYElementMatcherBlock *countMatcher = [GREYElementMatcherBlock matcherWithMatchesBlock:^BOOL(id element) {
if ([matcher matches:element]) {
count += 1;
}
return NO; // return NO so EarlGrey continues to search.
} descriptionBlock:^(id<GREYDescription> description) {
// Pass
}];
NSError *unused;
[[EarlGrey selectElementWithMatcher:countMatcher] assertWithMatcher:grey_notNil() error:&unused];
return count;
}
Step 2 Use % to select a random index
NSUInteger randomIndex = arc4random() % count;
Step 3 Finally use atIndex: to select that random element and perform action/assertion on it.
// Count all UIView's
NSUInteger count = [self elementCountMatchingMatcher:grey_kindOfClass([UIView class])];
// Find a random index.
NSUInteger randIndex = arc4random() % count;
// Tap the random UIView
[[[EarlGrey selectElementWithMatcher:grey_kindOfClass([UIView class])]
atIndex:randIndex]
performAction:grey_tap()];

Why increment inside function isn't working?

I try to make function run only one time during runtime, but it fires every time instead
var requestCount: Int = 0
func JSONRequest() {
if self.requestCount == 0 {
...some stuff
self.requestCount = requestCount + 1
} else {
println("JSONRequest dismissed")
}
During debugging I figured out that every time JSONRequest() runs it has value of self.requestCount equal to zero. For some reason it doesn't save increment and every time i call the function the self.requestCount is 0.
Why ? What am I doing wrong ?
Could it be that your code is in a ViewController which is being re-created each time (and therefore the count is re-initialized to zero each time)?
If so, you can do one of the following:
use a singleton - not always the cleanest but it works
use persistence (e.g., CoreData or NSUserDefaults)

how do i declare variables, compare them and then use them inside a function

i am developing an ea that requires me to compare the high of previous 2 bars and whichever one is higher, use that as a stop loss value.
same for opposite side trades, i need to compare previous 2 lows and use the lower one as stop loss value.
what i am doing is this:-
void onTick()
{
static int ticket=0;
double ab=(//calculation for ab);
double de=(//calculation for de);
if(Low[1]<Low[2])
double sll=Low[1];
if(Low[1]>Low[2])
double sll=Low[2];
if(buy logic comes here)
{
double entryPrice=////////;
double stoploss=sll-xyz;
double takeprofit=entryPrice+((entryPrice-stoploss)*3);
ticket = OrderSend(Symbol(),...entryPrice,stoploss,takeprofit,.....);
}
if(ticket == false)
{
Alert("Order Sending Failed");
}
}
the problem is i am not able to reference the values of sll and get an error message saying "sll undeclared identifier"
i am fairly new to programming and would appreciate if someone can help me out with this.
I have added most of the code for you to understand the logic.
you would have to declare them outside the scope of the if statements if you want to use variables anywhere else so instead of doing that take a look at this
double sll; // declare sll outside the if statements
if(Low[1]<Low[2])
sll=Low[1];
if(Low[1]>Low[2])
sll=Low[2];
if(buy logic comes here)
{
bool res = OrderSend(..........);
}
Judging by what you wrote, it looks like you may be using res somewhere else too which then you need to define outside of the if statement because scoping.

Random implementation of methods in cocos2d-iphone?

I have some "void" methods in my project using cocos2d-iphone and would like make them random. Unfortunately, I'v found only little information about genareting random numbers. Any help is appreciated!
If I understand correctly you want to call a random method, right?
Get your method signatures in an array:
NSArray* methods = #[#"myMethod1", #"myMethod2", #"myMethod3"];
Pick a method name:
NSString* method = methods[arc4random()%method.count];
Call it:
[self performSelector:NSSelectorFromString(method)];
It would be also wise to check that self can respond to that selector first.
Try this
.h
-(int) randomGenarete;
.mm
-(int) randomGenarete
{
int random_number = arc4random() % 100; // return random 0 to 99
return random_number;
}

Timing loop results

I got a little stuck and I'm hoping someone can point me in the right direction. I have an NSMutableArray that stores a sequence. I created an enumerator so that a while loop can get the content of the array one by one.
Everything works fine however I want the methods to be called with a 10 second gap in between each call. Right now it plays all at once (or in very quick order). What should I look at to create a delay in between method calls?
Below is what I got so far. Thanks!
NSEnumerator * enumerator = [gameSequenceArray objectEnumerator];
id element;
while(element = [enumerator nextObject])
{
NSLog(element);
int elementInt = [element intValue];
[self.view showButton:elementInt];
}
You almost certainly don't want to stick a "delay" in your loop, which will block the thread until it's over (and, unless your app is multi-threaded, block the entire thing). You could use multiple threads, but instead I'd probably split the loop out over repeated timed calls of another selector. Store the enumerator (or current index), and then look at NSObject's performSelector:awithObject:afterDelay:
So something like
[NSObject performSelector:#selector(some:selector:name:) withObject:objInstance afterDelay: 10]
where the selector will pickup the current enumerator, use it, advance it and schedule another call. Make sure you don't allow changes to the collection whilst this set of timed methods is executing.
This is what NSTimer is for. Use NSTimer to get each element in the array sequentially.
As an aside: you might want to take a look at Objective-C 2.0's Fast Enumeration
if gameSequenceArray is an array, then you don't need to use an enumerator:
NSTimeInterval time = 10;
for (id elementId in gameSequenceArray) {
[self.view performSelector:#selector(showButton:) withObject:elementID afterDelay:time];
}
and then you declare showButton:
- (void)showButton:(id)anElement {
...
}
If you end up passing your object enumerator around with a timer, know that you are not allowed to modify your array's contents until you are finished enumerating it.
So here was the solution that I came up with based on everyones input.
NSEnumerator * enumerator = [gameSequenceArray objectEnumerator];
NSTimeInterval time = 5;
for (NSString *element in enumerator) {
id elementId = element;
time++;
[self.view performSelector:#selector(showButton:) withObject:elementId afterDelay:time];
}
Thanks again for pointing me in the right direction everyone.

Resources