views:

106

answers:

4

Ok so I have this code

NSMutableArray *smartThings = [[NSMutableArray alloc] initWithCapacity:3];
NSMutableString *smartString = [NSString alloc];
int random;
int numOfThings = 1;
random = arc4random() % numOfThings;
smartString = [smartThings objectAtIndex:random];
UIAlertView *smartAlert = [[UIAlertView alloc] initWithTitle:@"Thing To Say" message:smartString delegate:self cancelButtonTitle:@"Thanks" otherButtonTitles:nil];
[smartAlert show];
[smartAlert release];

[smartThings release];

What it 'should' do is create a UIAlertView out of a string, and that string is created from an array of strings.

When I run it and press the button to call this code the program crashes. Please help

And yes i did hook up all the connections in IB.

+3  A: 

smartThings is empty throughout the execution of this snippet, even though you've pre-allocated space for 3 items, so -objectAtIndex will raise an NSRangeException, which would crash the program if not caught.

In addition, since smartThing is only intended to be a pointer to an object inside smartThings, you shouldn't alloc it, declaring it merely as NSString* will suffice.

codelogic
+1  A: 

It looks like you have a few problems:

  1. There are no strings added to smartThings, so there's nothing for smartString to point to.
  2. smartString should probably be declared as an NSString *, NSMutableString is for strings that you want to change the contents of.
  3. numOfThings is totally redundant. Use [smartThings length] to find out how many strings are in smartThings
Mark Bessey
A: 

Ok, I think I fixed it. here is my code

NSMutableArray *smartThings = [[NSMutableArray alloc] initWithObjects:@"It's still intact, just in lots of little pieces.",nil];
    NSMutableString *smartString;
    int random;
    int numOfThings = 1;
    random = arc4random() % numOfThings;
    smartString = [smartThings objectAtIndex:random];
    UIAlertView *smartAlert = [[UIAlertView alloc] initWithTitle:@"Smart Thing" message:smartString delegate:self cancelButtonTitle:@"Done" otherButtonTitles:nil];
    [smartAlert show];
    [smartAlert release];
    [smartThings release];

But when I press the button to call this code the simulator crashes.

Mr. Man
A: 

Ok I fixed it this time. I had it in the MainView.m file instead of the MainViewController.m file.

Mr. Man