Note that there are some explanatory texts on larger screens.

plurals
  1. POautoreleasing NSString in class method causing app crash in iOS
    text
    copied!<p>The error I receive is as follows:</p> <pre><code>int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, nil); //breakpoint that says Thread 1: Program Received Signal: "EXC_BAD_ACCESS". [pool release]; return retVal; } </code></pre> <p>My two questions can be found at the bottom of this post :)</p> <p>I am currently working on an assignment for an iOS programming class and have hit a road bump. </p> <p>I have found a fix, shown below, but it doesn't make sense to me. Check it out:</p> <pre><code>@implementation MyClass // This class method takes an (NSMutableArray *) and returns an NSString with its contents printed out. + (NSString *)myString:(NSMutableArray)anArray { // NSString *myString = [[NSString alloc] init]; OLD CODE THAT CAUSES MEMORY LEAK NSString *myString = [[[NSString alloc] init] autorelease]; //NEW CODE THAT RELEASES FIRST ALLOCATION OF myString WHEN THE FIRST stringByAppendingFormat: IS CALLED NSString *vp = VARIABLE_PREFIX; //#defined above to be @"% for (id object in anArray) { if ([object isKindOfClass:[NSString class]]) { if ([object hasPrefix:vp]) { myString = [myString stringByAppendingFormat:@"%@",[object substringFromIndex:1]]; }else{ myString = [myString stringByAppendingFormat:@"%@",object]; } }else if ([object isKindOfClass:[NSNumber class]]) { myString = [myString stringByAppendingFormat:@"%@",object]; } } return myString; //shouldn't I autorelease myString right before this line? NO NOT ANY MORE. THIS myString IS NOT THE ORIGINAL THAT I alloc-init, BUT AN AUTORELEASED OBJECT RETURNED BY THE stringByAppendingFormat: message. } </code></pre> <p>When I try to send the message <code>[myString autorelease];</code>, the program crashes with the above error. It is working fine now as shown above, but I do not understand why.</p> <p>Every time I send a message containing the "magic words" <code>alloc, init, copy</code> I have to call <code>release</code>, it don't I? Or are the rules different in a Class method (can the Class itself own a file?). I do not call <code>retain</code> in the object that is calling this file.</p> <h1>Here are my two questions:</h1> <ol> <li><p>Why does this crash when I try to release <code>theDescription</code> using <code>autorelease</code>?</p></li> <li><p>Does my code create a memory leak?</p></li> </ol> <p>This is my very first question on stack overflow! Thank you for your help!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload