Jonathan
Jonathan

Reputation: 15452

EXC_BAD_ACCESS with characterAtIndex, but not substringToIndex

I am new to Objective-C and as a very simple learning exercise, I have created a method to return the first initial of a variable storing a name:

-(NSString *)initial
{
    return [_name substringToIndex:1];
}

This works exactly as intended when I use substringToIndex, however if I instead use characterAtIndex I receive a EXC_BAD_ACCESS error.

Can anyone explain why one works and the other doesn't?

Upvotes: 0

Views: 279

Answers (2)

James
James

Reputation: 2376

Like yoprogramo stated, a character is not an NSString. Since your method is returning a pointer to a string, the char you're returning is being read as a pointer. When your program goes to read from that memory address, it's throwing the EXC_BAD_ACCESS.

Upvotes: 2

yoprogramo
yoprogramo

Reputation: 1306

characterAtIndex returns a char, not a (NSString *), probably the problem is in returning the wrong type.

Upvotes: 4

Related Questions