Datenshi
Datenshi

Reputation: 1191

NSString formatting, bad access

i get EXC_BAD_ACCESS while formatting string.

NSString *object = [[NSUserDefaults standardUserDefaults] stringForKey:@"ObjectNumber"];
NSString *pin = [[NSUserDefaults standardUserDefaults] stringForKey:[NSString stringWithFormat:@"Pin%i ",object.intValue]];
NSString *msg = [NSString stringWithFormat:@"%@N", pin];

NSString *msg2 = @"0001N";

NSLog(@"Sending %@", msg);

tcpConnection *Obj = [tcpConnection alloc];
[Obj loadUpConnection:msg];

If i use msg2 everything works fine. But if i use msg it gets exc_bad_access even though NSLog prints msg correctly.

Upvotes: 0

Views: 225

Answers (2)

Valentin Shamardin
Valentin Shamardin

Reputation: 3658

you have to initialize you *Obj.

tcpConnection *Obj = [tcpConnection alloc] init...

Upvotes: 1

Jasarien
Jasarien

Reputation: 58478

I suspect that your loadUpConnection: method isn't retaining its parameters.

It seems that there's a lot for you to learn in regards to objective-c.

I worry that this will confuse you more than help, but the msg2 variable is pointing to a static instance of the string "0001N" (because you hardcoded it at compile time the system creates a static instance to use). This is why it doesn't crash when you use msg2, but does when you use msg. msg is pointing to a dynamically allocated instance. The reference returned to you is 'autoreleased' which means it will be released at some point in the future (usually at the end of the run loop iteration). If your loadUpConnection: method doesn't retain it's parameters, then the msg string will be released before you try to use it, causing the EXC_BAD_ACCESS error. Because msg2 is a static instance, it will never be deallocated, hence it not crashing.

My only advice would be to continue learning - pick up a book, I recommend 'Programming in Objecive-C' by Stephen Kochan, or 'iPhone Programming A Big Nerd Ranch Guide' by Aaron Hillegass.

Upvotes: 3

Related Questions