How to convert a method name into a String - objective-c

I´m developing a little game right now and I want to have several levels.
So i´m asking if it´s the first time the app gets launched. If it´s like that the user will start at level1.
But if now i want to start another method.
I have methods like:
-(void)level1{};
-(void)level2{};
.
.
.
till level 100 or so.
So after if got the amount of times the app got started i want to call a method, which fits.
So i tried to make it like:
[self [NSString stringWithString:#"level%d", level]];
Because "level" has a number like 1,2,3...,100. So i tried to make it like level1,level2, level3, and so on.
But for that I get an error -> Unexpected interface name 'NSString': expected expression.
Can anyone please help me? Thanks in advance!
Peace!

You need to use NSSelectorFromString():
NSString* methodName = [NSString stringWithFormat:#"level%d", level];
SEL sel = NSSelectorFromString(methodName);
[self performSelector:sel];

Related

adding Dictionary(Object) to a MutableArray Objective C

Really new to Objective C, I'm trying to add these objects to a MutableArray. My problem is this, when I'm adding new books to the array by specifying the name of the book like this:
[self.bookData addObject:[self newBookWithTitle:#"some book" andAuthor:#"some author"]];
it works. However, I want to use 2 variables I've created to get the title and author but I keep getting an error saying that it expects a ":" from the code below (inputTitle and inputAuthor are my variables that grab from the textFields
[self.bookData addObject:[self newBookWithTitle:#"%#", _inputTitle andAuthor:#"%#", inputAuthor]];
Sorry, I've looked all over but can't find out whats wrong with my syntax and where to put the : it says it needs. Any help would be appreciated.
Get rid of the #"%#", in both places of the second line. Just pass _inputTitle and inputAuthor as-is assuming they are NSString objects.
[self.bookData addObject:[self newBookWithTitle:_inputTitle andAuthor:inputAuthor]];
BTW - do yourself a favor and make your code easier to read as well as easier to debug. Split the line in two:
NSString *book = [self newBookWithTitle:_inputTitle andAuthor:inputAuthor];
[self.bookData addObject:book];
I'm assuming newBookWithTitle:andAuthor: returns an NSString. Adjust as needed.

Obj-C Text fields, float values and SIGBART

I am writing an iOS application for (among many features) calculating alcohol content from sugar before and after fermentation for homebrewers. Now the problem is; every time I run my app in the simulator, it crashes with "Thread 1: Signal SIGBART" once I enter the UIViewController with the text fields, labels and buttons used in this function (in the implementation):
- (IBAction)calcAlc:(id)sender {
double ogVal = [[oGtext text]floatValue];
double fgVal = [[fGtext text]floatValue];
double alcoContent = ((1.05*(ogVal-fgVal))/fgVal)/0.79;
NSString *theResult = [NSString stringWithFormat:#"%1.2f",alcoContent];
alcContent.text = theResult;
}
I'm really stuck here -- any help is very appreciated. Thanks in advance!
You should check if fgVal is ever 0, since you are dividing by fgVal.
You will also want to use doubleValue instead of floatValue, since you are declaring them as double.
I think you should try float in place of double.
Now put break points on each and every method and debug it to get the exact point where you application is getting crashed and then you will be able to find the solution.
Also be sure to connect each and every ib outlet and action in your storyboard or nib(whatever you are using).
Please notify if it works..:)

How to use ios 6 challenge in game centre

Firstly,
I am fairly new to objective c / xcode dev so there is a good chance i am being a muppet. I have written a few simple apps to try things and my most recent one has been testing the gamecentre classes / functionality.
i have linked ok to leaderboards and achievements - but i can't get challenges working.
I have added the following code.... which is in my .m
GKLeaderboard *query = [[GKLeaderboard alloc] init];
query.category = LoadLeaderboard;
query.playerScope = GKLeaderboardPlayerScopeFriendsOnly;
query.range = NSMakeRange(1,100);
[query loadScoresWithCompletionHandler:^(NSArray *scores, NSError *error)
{NSPredicate *filter = [NSPredicate predicateWithFormat:#"value < %qi", scoreint];
NSArray *lesserScores = [scores filteredArrayUsingPredicate:filter];
[self presentChallengeWithPreselectedScores: lesserScores];
}
];
this code is basically taken from apple, just replacing the variable names....
this however gives an error on
[self presentChallengeWithPreselectedScores: lesserScores];
error Implicit conversion of an Objective-C pointer to 'int64_t *' (aka 'long long *') is disallowed with ARC
LoadLeaderboard is defined as a string
scoreint is defined as integer, thought this may be issue as not int64_t but that does not seem to make a difference.
I am sure for someone who has any kind of a clue this is a straightforward fix. But i am struggling at the moment. So if anyone can be kind and help a fool in need it would be most appreciated
Thanks,
Matt
welcome to Stack Overflow. I don't know your implementation of presentChallengeWithPreselectedScores method so I can't tell (although it looks like the method is taking a 64 bit integer and you're trying to feed it an array).
There are two ways to issue challenges:
1 - This is the easier way - if you've successfully implemented leader boards and score posting to game center, the challenges work out of the box in iOS6, the user can always view the leader board - select a submitted score (or a completed achievement) and select "Challenge Friend".
2 - The second way is to build a friend picker and let the user issue challenges within your game. But considering you're new to objective-c and game center, it's not so easy. But for your reference here is how you do it:
when you submit a GKScore object for the leaderboards - you can retain and use that GKScore object (call it myScoreObject) like this:
[myScoreObject issueChallengeToPlayers:selectedFriends message:yourMessage];
where selectedFriends is an NSArray (the friend picker should generate this) - the message is optional and can be used only if you want to send a message to challenged friends.

arc4random using input from textField

I am trying to use arc4random but it os causing my app to crash. On my view I have a text field and the user will enter a number, when the hit a button this number is used for the range, the code I use is as follows:
int myInt1 = [textfield.text intValue];
int fromNumber = 1;
int rnumber = (arc4random() % (myInt1 - fromNumber)) + fromNumber;
number1.text = [[NSString alloc] initWithFormat:#"%i",rnumber];
It will work if I use 50 for example instead of myInt1 but I need the user input. Any help is greatly appreciated.
I have noticed that it will work when there is a figure in the textfield, when this is left blank and the button is selected then the app crashed. In the console "Terminating in response to SpringBoard's termination" is displayed.
If the variable 50 is working then there is obviously something wrong with your text field's text. Most likely your text field is nil. Try checking back to your code and see if anything is influencing your app to become nil.
I will tell you this in case something similar happens next time. You should always try to debug your code, for example, instead of straight posting this to stack overflow with minimal code, try figuring out the problem yourself!
For example, a method identify what is wrong with your problem that I suggest you try now and feedback the results to me is checking if textfield is non-zero like below:
if (textfield) {
NSLog (#"Text field is not nil! GOOD!");
}
If the log is called in your console, you know your problem is that textfield is nil.

How to pass variable to other method?

I know this is a very beginner question, but I've been struggling to figure it out.
I'm trying to build an iOS game (using cocos2d) and so I have 2 sets of files
GameScene.h and gameScene.m
MainMenu1.h and MainMenu1.m
GameScene has the sharedcode I've leaned to put in.
I call my MainMenu1 - the user chooses how many players from a MenuItemwithImage and that calls ChoosePlayers
I can figure out which menu item was touched, but I need to pass the number of players back to GameScene
in GameScene I put in
-(void) setPlayers (nsinteger*) players
{
totalplayers = players;
}
so in mainmenu1 chooseplayers i did
[[GameScene SharedGameData] setPlayers : 2];
but that doesn't work.
I'm sorry, I don't have the code in front of me (not until tonight); i've been searching for hours and can't figure it out.
Your method format is incorrect. It should be:
-(void)setPlayers:(NSInteger)players;
NSInteger is not a pointer either.
To pass multiplie values, you coud either pass in an array, or:
-(void)setPlayers:(NSInteger)firstValue withSecondValue:(NSInteger)secondValue; and when you want to call it, it would look like this:
[[GameScene SharedGameData] setPlayers:2 withSecondValue:4];
Hi it would be good if you could post some more detail about the errors you are receiving (if any?), this would helpt to diagnose the problem but looking at you code it i think that you need to change the
-(void) setPlayers (nsinteger*) players
to
-(void) setPlayers :(nsinteger*) players
hope this helps!