I've got a MFMailComposeViewController object that I'm releasing in my Email button's callback, simply because I created it, and I think my doing so is intermittently but not always crashing my app.
How can I use Xcode's instrumentation program to detect such a situation?
Thanks.
You can set the NSZombieEnabled environment variable to YES (Product > Edit Scheme…, the select Run (Product Name), click the Arguments tab and edit the list of environment variables). With NSZombie, objects will not be deallocated but turned into zombies. Messaging them will log an error to the console instead of crashing with EXC_BAD_ACCESS. That way you can find out if it’s really the MFMailComposeViewController that’s causing trouble.
But retaining and releasing the view controller might not even be necessary. If you present the MFMailComposeViewController immediately after creating it and don’t use it anymore after it’s been dismissed, there’s no need to retain it:
- (IBAction)composeMessage:(id)sender {
MFMailComposeViewController *mailComposeViewController = [[[MFMailComposeViewController alloc] init] autorelease];
mailComposeViewController.mailComposeDelegate = self;
[self presentModalViewController:mailComposeViewController animated:YES];
}
- (void)mailComposeController:(MFMailComposeViewController *)mailComposeViewController didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
// Present error to the user if failed
[self dismissModalViewControllerAnimated:YES];
}
Related
Currently I didn't use ARC in my app, and I tried to create a NSAlert object as a local variable, at the end of function, I didn't release it.
I expected that the app crash with that, the function code is here.
#define GLOBAL_VARIABLE 0
NSString *msgText = [self.defaultValueTextFiled stringValue];
NSString *informativeText = #"Informative Text";
#if !GLOBAL_VARIABLE
NSAlert *alertView = nil;
#endif
if (alertView == nil)
{
alertView = [[NSAlert alloc] init];
[alertView setMessageText:msgText];
[alertView setInformativeText:informativeText];
NSTextField *accessory = [[NSTextField alloc] initWithFrame:NSMakeRect(0,0,200,22)];
[accessory setStringValue:#"accessory result"];
[alertView setAccessoryView:accessory];
}
NSView *accessory= nil;
NSInteger result = [alertView runModal];
if (result == NSAlertAlternateReturn)
{
accessory = [alertView accessoryView];
if (accessory != nil)
{
NSTextField *txtFiled = (NSTextField *)accessory;
NSLog(#"%ld", [accessory retainCount]);
NSString *str = [txtFiled stringValue];
NSLog(#"%ld", [accessory retainCount]);
[self.resultValueTextField setStringValue:str];
NSLog(#"%ld", [accessory retainCount]);
}
}
Questions:
(1) There is no [alertView release] in the end, why not crash? It has even no leaks.
(2) Refer to here , the accessory view shouldn't be release. However, I tried to release the view before [alertView runModal], then get its stringValue later, that could works. Why?
(3) The return value of function retainCount is interesting. When I created the alertView object, the retainedCount of alertView is 3. (Why?)
Before [alertView setAccessoryView:accessory], the accessory's retainedCount is 1, then it changed to 2 after executing it. That's normal and right. However, the log result for the above code, they're 20, 21, 22. How did they come from?
Thanks for your attention!
It does leak. Put a breakpoint on dealloc (or create a subclass of NSAlert and add a log statement to dealloc) to show this
The accessry view should be released. You alloc it and then it would be retained by the alertView
Here's a concise guide on when to use retainCount.
The rules for memory management are generally quite simple. Most problems come from overthinking them and trying to guess what other parts of the system are going to do, rather than just following the rules as written.
The first rule of Memory Management:
Use ARC.
If you cannot follow rule one (for instance, you are developing for OS X 10.5 as I do), then here are the rules:
You must balance each call you make to +alloc…, +new…, -…copy… or -retain with a call to -release or -autorelease.
That's really it. Everything else is really just commentary to help you follow that rule. So, you called [NSAlert alloc] and [NSTextField alloc], you need to call release on those objects.
Why doesn't it crash?
Because a leak is not going to crash unless it causes you to run out of memory.
Why doesn't it leak?
The most likely cause is that you're only running it once and then expecting Instruments to detect the leak. It may not show up if you only run it once. It depends on how NSAlert is internally implemented. Instruments finds leaks by walking all the pointers in the system and determining if any accessible pointers still reference a piece of allocated memory. There are many cases when a "leak is not a leak."
But this also suggests you're not running the static analyzer, because the analyzer should definitely have detected that leak. Run the static analyzer (Cmd-Shift-B) all the time and clean up what it finds.
the accessory view shouldn't be release.
That's not what the link you reference says. You shouldn't add an extra release. But in the referenced code, you'll notice that they release the view to balance their own +alloc.
… retainCount …
Never use -retainCount. Not even for debugging. Not even for anything else. There is no point at which retainCount is going to return you a piece of information that is going to be more enlightening than confusing. Why is it greater than you think it should be? Because other objects are retaining the alert view? Which objects? That's not your business. That's an internal implementation detail, subject to change. It could be pending autorelease calls, which show up temporarily as a "too high retainCount". It could be the run loop. It could be an internal controller. It could be anything. Calling retainCount tells you nothing useful.
Now that you understand manual memory management, switch to ARC and think about object graphs rather than retain counts. It is a much better way to deal with memory.
I am currently doing the CS193P lessons via iTunesU and the teacher mentioned the Build and Analyze option several times. He said that it was a nice tool and fun to play with.
So I tried, and noticed that it doesn't work, or that I don't understand how it should work (I think the last option).
I have a few memory leaks, and it is not warning me at all! I saw online that a blue thing should appear telling me it is a leak, but I don't see anything although I'm doing NSDictionary *dict = [[NSDictionary alloc] init];.
How is it supposed to work? From what I read on the internet I thought it should signal potential leaks. What am I doing wrong?
I'm using XCode 3.2.5.
Thanks.
Update:
This is a kind of bug, I think.
When I declare this in the interface like NSDictionary *dict; and initialize it (but nowhere deallocating it) it says nothing.
When I declare and initialize it in - (void) init and don't release it in there like:
- (void) init {
if(self = [super init])
NSDictionary *dict = [[NSDictionary alloc] init];
return self;
}
It does signal a leak. Why? Is this because of my settings? Is this a bug? If it is a bug, where and how should I report it?
It's giving you a warning because you're not deallocating it.
-(void)dealloc{
[super dealloc];
[dict dealloc];
}
It's not warning you because you should be able to release the objects as soon as you create them, and the analyzer goal is to alert you on possible leaks in your code.
You can either use autorelease, or you dealloc the object you create manually.
P.S., little curiosity: why are you using Xcode 3.2.5?
Don't know exactly if that version can, but in the latest versions of Xcode, when you run that tool, you are able to see WHAT object you are deallocating with the means of some arrows with explanation, something like
I just found out that a reboot and restart of Xcode will bring it back.
In most systems, the default behaviour for "open a new window" is that it appears at the front. This doesn't happen in Cocoa, and I'm trying to find the "correct" way to make this standard behaviour. Most things I've tried only work for a maximum of one window.
I need to open multiple windows on startup:
(N x NSDocuments (one window each)
1 x simple NSWindowController that opens a NIB file.
Things that DON'T work:
Iterate across all the NSDocuments I want to open, and open them.
What happens? ... only the "last" one that call open on comes to the front - the rest are hidden, invisible, nowhere on the screen, until you fast-switch or use the Window menu to find them.
Code:
...documents is an array of NSPersistentDocument's, loaded from CoreData...
[NSDocumentController sharedDocumentController];
[controller openDocumentWithContentsOfURL:[documents objectAtIndex:0] display:YES error:&error];
Manually invoking "makeKeyAndOrderFront" on each window, after it's opened
What happens? nothing different. But the only way I can find to get the NSWindow instance is so horribly hacky it seems totally wrong (but is mentioend in several blogs and mailing list posts)
Code:
[NSDocumentController sharedDocumentController];
NSDocument* openedDocument = [controller openDocumentWithContentsOfURL:[documents objectAtIndex:0] display:YES error:&error];
[[[[openedDocument windowControllers] objectAtIndex:0] window] makeKeyAndOrderFront:nil];
...I know I'm doing this wrong, but I can't find out why/what to do differently :(.
Something that works, usually, but not always:
As above, but just use "showWindow" instead (I took this from the NSDocument guide).
Bizarrely, this sometimes works ... even though it's the exact code that Apple claims they're calling internally. If they're calling it internally, why does it behave different if I re-invoke it after they've already done so?
[[[openedDocument windowControllers] objectAtIndex:0] showWindow:self];
You can just open all the documents without displaying and then tell the documents to show their windows:
NSArray* docs = [NSArray arrayWithObjects:#"doc1.rtf", #"doc2.rtf",#"doc3.rtf",#"doc4.rtf",nil];
for(NSString* doc in docs)
{
NSURL* url = [NSURL fileURLWithPath:[[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:doc]];
NSError* err;
[[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:url display:NO error:&err];
}
[[[NSDocumentController sharedDocumentController] documents] makeObjectsPerformSelector:#selector(showWindows)];
Won't this work?
For 10.6 or greater
[[NSRunningApplication currentApplication] activateWithOptions:(NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps)];
This often has something to do with the app itself: your other windows are behind other apps (in particular, behind Xcode!), and would have appeared with a Hide Others command.
The solution to that problem would be that after you send showWindow to all of your windows (making sure you do the key one last), you tell the app to come forward, relative to other apps.
NSApp.activateIgnoringOtherApps(true) // Swift
or
[NSApp activateIgnoringOtherApps:YES]; // Objective-C
See also: How to bring NSWindow to front and to the current Space?
I'm making a non-garbage-collected MacFUSE Cocoa application, inside of which I want to use a GCD block as a delegate. However, my program crashes during the invocation of the block, leaving only an EXC_BAD_ACCESS in its trail.
My program uses a framework built agains the Mac OS 10.5 SDK that does not support garbage collection (nor 64 bits) and the MacFUSE framework. The program builds with no warning or error as a 32-bit program. Other build settings (such as optimization level) were left to their original values.
So I have my application controller, from which I create this block and call runWithContinuation:
AFSPasswordPrompt* prompt = [[AFSPasswordPrompt alloc] initWithIcon:icon];
dispatch_block_t continuation = ^{
archive.password = prompt.password;
[self mountFilesystem:fsController];
[prompt performSelectorOnMainThread:#selector(release) withObject:nil waitUntilDone:NO];
};
[prompt runWithContinuation:continuation];
runWithContinuation: retains the block and instantiates a nib. The block is called only once the user dismisses the password prompt by pressing the "Open" button.
-(void)runWithContinuation:(dispatch_block_t)block
{
continuation = [block retain];
[passwordPrompt instantiateNibWithOwner:self topLevelObjects:NULL];
imageView.image = image;
[window makeKeyWindow];
}
-(IBAction)open:(id)sender
{
continuation();
[self close];
}
-(void)close
{
[window close];
[continuation release];
}
My problem is that when I hit continuation(), my program triggers an EXC_BAD_ACCESS, and the last stack frame is called ??. Right under it is the open: method call.
I really don't know where it's coming from. NSZombies are enabled, and they don't report anything.
Any ideas?
try copying the block instead of retaining it. A block lives on the stack until you call copy, then it is copied to the heap.
I'm working on an app that uses a navigation controller. When I build, I get no errors or warnings. I've defined a method myMethod in FirstViewController.m file, then in viewDidLoad I call the method with [self myMethod];.
When I built and ran from the Console, I got nothing. So I put NSLog() statements like so:
-(void) viewDidLoad {
NSLog(#"Entering viewDidLoad");
[self myMethod];
NSLog(#"Called myMethod");
[super viewDidLoad];
}
The Console never returns the second NSLog statement, leading me to believe that the app crashes while calling the method.
I've tried this with the simulator set to iOS 4.0.1 as well as iOS 4.1. I'm building against the iOS 4.1 SDK. I really appreciate any help you can offer.
Update: I ran the Debugger, which seems to show the problem being in myMethod. I only make it through a few lines of code in that method before I receive "EXC_BAD_ACCESS". The lines of code are:
-(void)myMethod {
NSMutableArray *someStuff;
NSMutableArray *someMoreStuff;
stuffSections=[[NSMutableArray alloc] initWithObjects:#"Some Stuff",#"Some More Stuff",nil];
someStuff=[[NSMutableArray alloc] init];
someMoreStuff=[[NSMutableArray alloc] init];
[someStuff addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:#"Item Name",#"name",#"Item Picture.png",#"picture",#"http://theurl.net/",#"url",#"1",#"itemCode",nil]];
But it appears that I can't get past this first attempt to add something to the someStuff array.
Looks like there is a problem in "myMethod". If I had to guess, I would say you are trying to reference an object that was auto-released and not retained.
You're missing the alloc when initializing someStuff and someMoreStuff. It should be
someStuff = [[NSMutableArray alloc] init];
someMoreStuff = [[NSMutableArray alloc] init];
Have you cross checked the two MutableArrays? Do they have been allocated successfully? You get "EXC_BAD_ACCESS" when the app got into a corrupted state that is usually due to a memory management issue. I guess the arrays are not allocated.
Try allocating this way.
NSMutableArray * someStuff = [[NSMutableArray alloc]initWithCapacity:3];
NSMutableArray * someMoreStuff = [[NSMutableArray alloc]initWithCapacity:3];
add a breakpoint there are check in the debug area and confirm whether they are being allocated successfully. If there is a memory to each of these array, then they are allocated.