Search code examples
objective-cnsmutablestring

Bad Access when trying to access a Mutable Array with an NSMutableString


I synthesized an NSMutableArray called email, which is part of an object Person. The email array contains pointers to several NSMutableString objects.

@property (strong) NSMutableArray *email;
@synthesize email = _email;

The string was declared (in the init method of the email object) as follows:

NSMutableString *s = [NSMutableString stringWithFormat:@"Blah"];

With this, I get a bad access error when I later executed an [email count] command in a different method. I use automatic retain counting ARC. Why does this happen?

EDIT: It turned out to be important that the output of [email count] was printed using %@, which won't work most of the time, see below.


Solution

  • Figured it out, I think.

    Makes it glaringly obvious how green I am with Cocoa / Objective C. I was printing a test message as follows:

    NSLog (@"%@",[[p email] count]);

    But the count method returns an unsigned long (or NSInteger), and as soon as I changed it into

    NSLog (@"%ul",....

    it worked. Things can be so easy and hard at the same time :-(

    so, memo to me:

    if a number is returned, make sure you want to print the object it points to (%@), it may be invalid!!