Is it possible to program multiple UIAlertViews for one IBAction in Xcode to show at random. For example: I am making an app with multiple questions shown at random, when the submit button is pressed, an alert is shown saying if the answer is correct or not. I want there to be different messages for the alert such as one time it shows one message, then the next time it shows a different message at random. How would I program this?
Asked
Active
Viewed 597 times
2 Answers
2
In your .h:
@interface MyViewController : UIViewController {
NSArray *messages;
}
@property (nonatomic, retain) NSArray *messages;
In your .m
@implementation MyViewController
@synthesize messages;
- (dealloc) {
[messages release];
}
- (void)viewDidLoad {
messages = [[NSArray alloc] initWithObjects:@"Funny Message", @"Even Funnier Message", @"Hilarious message", @"ROFL", @"OK this is getting boring...", nil];
}
When you need an alert:
NSUInteger messageCount = [messages count];
int randomMessageIndex = arc4random() % messageCount;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:[messages objectAtIndex:randomMessageIndex] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];

Alex Coplan
- 13,211
- 19
- 77
- 138
-
It says that messages is an undeclared identifier... What do I need to do to fix that? – cory ginsberg Aug 12 '11 at 01:31
-
When I run the code, the program works for one question, but it then crashes and shows the error "Program received signal: "EXC_BAD_ACCESS"" What am I doing wrong? I have copy and pasted your code so I know that it's all typed correctly. – cory ginsberg Aug 12 '11 at 13:54
1
define the following macro for the project:
for the msg section as try a Array with random Index
#define KAlert(TITLE,MSG) [[[[UIAlertView alloc] initWithTitle:(TITLE)
message:(MSG)
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] autorelease] show]
Which could be used as simple call:
KAlert(@"Title", @"Message");
or KAlert(@"Title",@"[youarray objectatindex:randindex]");

Karthikeyan
- 1,790
- 12
- 19