I have some abbreviated iOS Objective-C sample code (simplified from a larger project) that causes a crash in NSUndoManager that I can't explain.
Namely, when an object that is only held onto by the NSUndoManager deallocs (because it's beyond the levels of undo), and, according to the docs calls removeAllActionsWithTarget:self, I get an EXC_BAD_ACCESS.
// SimpleViewController.m
#interface ViewController ()
#property (nonatomic, strong) NSUndoManager *undoManager;
#end
#implementation ViewController
#synthesize undoManager;
// called from a simple button
- (IBAction)doItTapped:(id)sender
{
CoolObject *object = [CoolObject new];
object.undoManager = self.undoManager;
// according to docs, object will be retained by NSUndoManager here
// but target will not (which should be okay)
[self.undoManager registerUndoWithTarget:self selector:#selector(notCool:) object:object];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.undoManager = [NSUndoManager new];
self.undoManager.levelsOfUndo = 3;
}
and
// CoolObject.m
#implementation CoolObject
- (void)dealloc
{
[self.undoManager removeAllActionsWithTarget:self];
}
#end
After the 4th tap of the button (levelsOfUndo + 1), it crashes.
If I swap NSUndoManager with GCUndoManager, no crash.
Tested in iOS 10.2 sim and devices.
Thanks for any ideas!
Their are chances that you might be getting this error because self.undoManager is not retained at that point where you are using it. When the object is already deallocated and you try to access it, you will get bad access exception.
Try to change your code from this:
CoolObject *object = [CoolObject new];
to this:
#interface ViewController (){
CoolObject *object;
}
#property (nonatomic, strong) NSUndoManager *undoManager;
#end
#implementation ViewController
- (IBAction)doItTapped:(id)sender
{
object = [CoolObject new];
object.undoManager = self.undoManager;
// according to docs, object will be retained by NSUndoManager here
// but target will not (which should be okay)
[self.undoManager registerUndoWithTarget:self selector:#selector(notCool:) object:object];
}
#end
Hope this will help.
Just like me, you seem to have misinterpreted the admittedly inaccurately written documentation. The docs talk about "target", "object" and "target object" as if they were different things when they really mean exactly one and the same: the (id)target parameter of -removeAllActionsWithTarget:
In other words, in my opinion you should not need to call -removeAllActionsWithTarget: inside of CoolObject at all because CoolObject has been specified as the object of -registerUndoWithTarget:selector:object: whereas the target is your ViewController.
You may have to call -removeAllActionsWithTarget: in your NSViewController's -dealloc but even that is unnecessary in your example because your NSViewController owns the NSUndoManager and thus ViewController won't go away before undoManager does.
Related
I have an object which inherits from the MKPlacemark class of MapKit. I have a method launch during viewDidLoad of my ViewController that creates such object (alloc + init) and pass it to a MapView as follows
[self.mapView addAnnotation:<my instance of my class inheriting MKPlacemark>]
However, when I launch my program, I get the following error message:
An instance 0x9a5d650 of class <name of my class> was deallocated while key value
observers were still registered with it. Observation info was leaked, and may even
become mistakenly attached to some other object. Set a breakpoint on
NSKVODeallocateBreak to stop here in the debugger.
Note that I use ARC. Can anyone tell me how can I avoid such deallocation?
Thanks !
EDIT: My problem is not the warning in itself, it is that I do not want this object to be deallocate at that moment...
EDIT2: The code of the class is the following
The .h file looks like this
#interface OPTCreatureMark : MyMark
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
-(id)initWithCoordinate:(CLLocationCoordinate2D)coordinate;
#end
and the .m like that
#implementation MyMark
#synthesize coordinate;
-(id) initWithCoordinate:(CLLocationCoordinate2D)coordinate_ {
if (self = [super initWithCoordinate:coordinate_ addressDictionary:nil]) {
self.coordinate=coordinate_;
return self;
} else {
return nil;
}
}
#end
If you are indeed using KVO, it sounds like you need to remove the observer in your object's dealloc method like so:
[self removeObserver:self.myDelegate forKeyPath:#"zoom"];
Otherwise messages could be sent to a deallocated instance of your class (which can no longer respond because it's been deallocated), thus causing an exception.
I am developing an ARC enabled project. From a view controller I am pushing MyClass,
- (void)pushMyClass {
MyClass *myClass = [[MyClass alloc] init];
[self.navigationController pushViewController:myClass animated:YES];
}
After doing some operations I am popping MyClass. The problem here is that MyClass is not getting deallocated. Following is how the classes look.
/* MyHelperClassDelegate */
#protocol MyHelperClassDelegate <NSObject>
- (void)helperDidFinishHelping:(MyHelperClass *)helper;
#end
/* MyHelperClass Interface */
#interface MyHelperClass : NSObject {
__weak id <MyHelperDelegate> delegate;
}
#property(nonatomic, weak) id<MyHelperDelegate> delegate;
- (void)startHelping;
#end
/* MyHelperClass Implementation */
#implementation MyHelperClass
#synthesize delegate;
- (void)dealloc {
delegate = nil;
}
/* MyClass */
#interface MyClass : UIViewController <MyHelperClassDelegate> {
MyHelperClass *helper;
}
#implementation MyClass {
- (void)dealloc {
helper.delegate = nil;
}
- (void)getHelp {
helper = [MyHelperClass new];
helper.delegate = self;
[helper startHelping];
}
- (void)helperDidFinishHelping:(MyHelperClass *)helper {
}
}
MyHelperClass calls a web service using NSMutalbleURLRequest & NSURLConnection to fetch some data and saves it to user defaults.
One thing to notice here is, if I comment the line helper.delegate = self;, then MyClass gets deallocated.
What to do to make MyClass get deallocated when it is popped out of navigation controller?
Thanks.
Your delegate code looks correct (except your use of an ivar, you don't show a #synthesize so you may have _delegate and delegate both). Its quite likely that something else is retaining MyClass. What I suggest you do is add a NSLog to your MyClass dealloc. Then push it, and immediately hit the back button and see if its dealloc'd or not. If not, then take a hard look at what you do in viewDidLoad et al and start commenting out sections of that code until you can get the dealloc.
Also, I assume you don't keep a strong reference in the class that pushes the MyClass object.
I agree with Chuck that one cannot say much from the code provided. But one reason why the MyClass object is not deallocated might be that it is retained by your helper object since delegate is declared as strong, and the MyClass object has the property helper also declared as strong. In this case you had a retain cycle, and none of them can be released.
The trick could possibly lie within the fact that you use NSURLConnection. It is not specified how you use this class with the code that you've provided, but please note the special considerations referenced in the NSURLConnection class reference:
Special Considerations: During the download the connection maintains a
strong reference to the delegate. It releases that strong reference
when the connection finishes loading, fails, or is canceled.
I need to get things clear about Objective-C memory management:
If I declare an object in the class header as ivar without #property:
#interface MyFacebooDelegate : UIViewController
{
TableViewController *tableController;
}
...
#end
and some where in the code for example in - (void)viewDidLoad I do :
tableController = [[TableViewController alloc] init];
so where is best way to release it. What if I make the instant object a property what will be the different? and how the memory management will be too
#interface MyFacebooDelegate : UIViewController
{
TableViewController *tableController;
}
...
#end
#property (nonatomic, strong) TableViewController *tableController;
What the following syntax do exactly for the object viewController:
.h
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) ViewController *viewController;
#end
.m
#implementation AppDelegate
#synthesize window = _window;
#synthesize viewController = _viewController;
- (void)dealloc
{
[_window release];
[_viewController release];
[super dealloc];
}
.....
#end
If I want to return an object through a method to another class, do I need to autorelease it in the method body first and then retain it in receiver side?
for example this method what exactly to do in the method body and in the receiver side too:
-(NSString *)getFriendId
{
NSArray *ar = [NSArray arrayWithObjects:#"1",#"2",#"3", nil];
return [ar objectAtIndex:0];
}
I know this a lot but I am really confused and need your help.
1) best way is in dealloc; or right before re-setting it.
2) a property does the retain/release for you. But WARNING! You keep mixing up things. You use "strong" here, which relates to ARC. If you really insist on using classic retain/release (you shouldn't) then use (nonatomic, retain) instead.
3) Your properties get deallocated on dealloc. Again, strong is wrong here.
4) Yes. Ideally you should. Another reason why ARC is awesome, it does this all for you, automatically.
tl;dr: Use ARC. Never go back. (But still learn manual memory management)
ARC is the answer for your all memory management question. Very import note on Strong and Weak property in addition to ,
iOS Strong property: So strong is the same as retain in a property declaration before ARC. For ARC projects I would use strong instead of retain, I would use assign for C primitive properties.
iOS outlets should be defined as declared properties. Outlets should generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong. Outlets that you create will therefore typically be weak by default, because: Outlets that you create to, for example, subviews of a view controller’s view or a window controller’s window, are arbitrary references between objects that do not imply ownership.
Suppose I have a view controller like this:
#interface ControllerA : viewcontroller{
NSString * __strong a;
}
#end
and in viewDidLoad function I set
a = [[NSSString alloc] init];
And in another ControllerB,
{
ControllerA * controllerA = [[ControllerA alloc] init];
}
Will controllerA's member be released?
Yes, the string pointed to by a will be released when controllerA is deallocated. You don't need to set it to nil yourself.
Transitioning to ARC Release Notes is currently the place to look for more information about working with ARC. One important point that it makes is that you may still need a custom -dealloc if your class needs to do anything other than releasing instance variables when it's instances are deallocated.
You never need to set a variable to nil in ARC unless you want to ensure its deallocation as soon as possible (i.e. [myObject release] under non-ARC code). All iVars will be automatically released when the object is deallocated.
There is a well known bug in iOS 5 when using ARC and Zombies enabled that can prevent ivars from being released: Technical Q&A QA1758.
Otherwise, the ivars will be automatically released.
Update 2:
After spending, quite literally, several hours diagnosing and documenting the failure of ivars to be released in my iOS 5 project this morning, I discovered that instance variables are not released in ARC projects if zombies are turned on and run on iOS 5. About to update my answer with these remarkable findings, quite independently, Calin pointed out to me that this is well known behavior. Technical Q&A QA1758. Thanks Calin!
My sample project is at https://github.com/robertmryan/arc-problem-project
Update:
I had previously claimed that this was incorrect and that vars and properties would not be deallocated unless you set them to nil. I provided the below code as an example. This is taken from a real ARC test project and I even recreated it with another view controller with absolutely nothing in it except the code below to confirm. After a well-deserved chorus of dissents, I put this code sample in a new project, and the ivar was deallocated, as it should be.
So it must be something about the project in question. I've since taken absolutely everything out of that project except the below code (and the view controller that performs the push segue, so that I can pop back to it to demonstrate the deallocation), and the problem persists. If I copy the code (and storyboard) to a new project, it works fine. Very, very strange and I will dig into this more. If you want to see my project, it's at https://github.com/robertmryan/arc-problem-project. Maybe someone else can see what the problem is. I know I can just discard this project (it wasn't even a production app, just a testing platform), but it's worrying that ARC's dealloc can just magically not work properly.
Anyway, to be clear, your ivars are released as the parent object is released. I don't know why my is not releasing in the case below, but that's immaterial to the original question.
// ArcTestViewController.m
#import "ArcTestViewController.h"
#pragma mark - IvarObject
#interface IvarObject : NSObject
#end
#implementation IvarObject
- (void)dealloc
{
NSLog(#"%s", __FUNCTION__);
}
#end
#pragma mark - ArcTestViewController
#interface ArcTestViewController ()
{
IvarObject __strong *_ivarObject;
}
#end
#implementation ArcTestViewController
- (void)dealloc
{
NSLog(#"%s", __FUNCTION__);
// _ivarObject = nil;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_ivarObject = [[IvarObject alloc] init];
}
#end
When I do this with the =nil statement in the dealloc method commented out, I see the following on my console:
2012-07-12 10:33:33.644 test4[36045:11903] -[ArcSimpleTestViewController dealloc]
When I uncomment that =nil statement in my dealloc, I see the following:
2012-07-12 10:35:23.117 test4[36083:11903] -[ArcSimpleTestViewController dealloc]
2012-07-12 10:35:23.119 test4[36083:11903] -[IvarObject2 dealloc]
To my retraction above, when I put this same code in a new project, I see the deallocs whether I nil or not.
Rob Napier provided the code sample below (I appreciate him and others taking the time), but even the above code works fine when I put it in another project, but in my current project, it doesn't deallocate properly!
Update from Rob Napier: Simpler example (all in one file) that demonstrates how this works. Put this in a file and compile as indicated:
// arc.m
// Compile with:
// clang -fobjc-arc -framework Foundation -o arc arc.m
#import <Foundation/Foundation.h>
#pragma mark - IvarObject
#interface IvarObject : NSObject
#end
#implementation IvarObject
- (void)dealloc
{
NSLog(#"%s", __FUNCTION__);
}
#end
#pragma mark - PropertyObject
#interface PropertyObject : NSObject
#end
#implementation PropertyObject
- (void)dealloc
{
NSLog(#"%s", __FUNCTION__);
}
#end
#pragma mark - ArcTest
#interface ArcTest : NSObject
{
IvarObject __strong *_ivarObject;
}
#property (nonatomic, strong) PropertyObject *propertyObject;
#end
#implementation ArcTest
#synthesize propertyObject = _propertyObject;
- (void)dealloc
{
NSLog(#"%s", __FUNCTION__);
// _ivarObject = nil;
// _propertyObject = nil;
}
- (void)assignStuff
{
_ivarObject = [[IvarObject alloc] init];
self.propertyObject = [[PropertyObject alloc] init];
}
#end
int main () {
ArcTest *test = [[ArcTest alloc] init];
[test assignStuff];
test = nil;
NSLog(#"End program");
}
This question already has answers here:
How do I create delegates in Objective-C?
(20 answers)
Closed 9 years ago.
What is a "delegate" in Objective C's iPhone development?
A delegate is a pointer to an object with a set of methods the delegate-holder knows how to call. In other words, it's a mechanism to enable specific callbacks from a later-created object.
A good example is UIAlertView. You create a UIAlertView object to show a short message box to users, possibly giving them a choice with two buttons like "OK" and "Cancel". The UIAlertView needs a way to call you back, but it has no information of which object to call back and what method to call.
To solve this problem, you can send your self pointer to UIAlertView as a delegate object, and in exchange you agree (by declaring the UIAlertViewDelegate in your object's header file) to implement some methods that UIAlertView can call, such as alertView:clickedButtonAtIndex:.
Check out this post for a quick high-level intro to the delegate design pattern and other callback techniques.
References:
UIAlertView class reference
UIAlertViewDelegate class reference
Apple's guide to Delegates and Data sources
See this discussion
A delegate allows one object to send messages to another object when an event happens. For example, if you're downloading data from a web site asynchronously using the NSURLConnection class. NSURLConnection has three common delegates:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
One or more of these delegates will get called when NSURLConnection encounters a failure, finishes successfully, or received a response from the web site, respectively.
Delegates are a design pattern; there is no special syntax or language support.
A delegate is just an object that another object sends messages to when certain things happen, so that the delegate can handle app-specific details the original object wasn't designed for. It's a way of customizing behavior without subclassing.
I think this Wikipedia article describes it best: http://en.wikipedia.org/wiki/Delegation_pattern
It is "just" an implementation of a design pattern and very common in Objective-C
I think all these answers make a lot of sense once you understand delegates. Personally I came from the land of C/C++ and before that procedural languages like Fortran etc so here is my 2 min take on finding similar analogues in C++ paradigm.
If I were to explain delegates to a C++/Java programmer I would say
What are delegates ? These are static pointers to classes within another class. Once you assign a pointer, you can call functions/methods in that class. Hence some functions of your class are "delegated" (In C++ world - pointer to by a class object pointer) to another class.
What are protocols ? Conceptually it serves as similar purpose as to the header file of the class you are assigning as a delegate class. A protocol is a explicit way of defining what methods needs to be implemented in the class who's pointer was set as a delegate within a class.
How can I do something similar in C++? If you tried to do this in C++, you would by defining pointers to classes (objects) in the class definition and then wiring them up to other classes that will provide additional functions as delegates to your base class. But this wiring needs to be maitained within the code and will be clumsy and error prone. Objective C just assumes that programmers are not best at maintaining this decipline and provides compiler restrictions to enforce a clean implementation.
I try to elaborate it through simple program
Two Classes
Student.h
#import <Foundation/Foundation.h>
#interface Student : NSObject
#property (weak) id delegate;
- (void) studentInfo;
#end
Student.m
#import "Student.h"
#implementation Student
- (void) studentInfo
{
NSString *teacherName;
if ([self.delegate respondsToSelector:#selector(teacherName)]) {
teacherName = [self.delegate performSelector:#selector(teacherName)];
}
NSLog(#"\n Student name is XYZ\n Teacher name is %#",teacherName);
}
#end
Teacher.h
#import <Foundation/Foundation.h>
#import "Student.h>
#interface Teacher: NSObject
#property (strong,nonatomic) Student *student;
- (NSString *) teacherName;
- (id) initWithStudent:(Student *)student;
#end
Teacher.m
#import "Teacher.h"
#implementation Teacher
- (NSString *) teacherName
{
return #"ABC";
}
- (id) initWithStudent:(Student *)student
{
self = [ super init];
if (self) {
self.student = student;
self.student.delegate = self;
}
return self;
}
#end
main.m
#import <Foundation/Foundation.h>
#import "Teacher.h"
int main ( int argc, const char* argv[])
{
#autoreleasepool {
Student *student = [[Student alloc] init];
Teacher *teacher = [[Teacher alloc] initWithStudent:student];
[student studentInfo];
}
return 0;
}
EXPLANATION :::
From main method when initWithStudent:student will execute
1.1 Teacher's object's property 'student' will be assigned with student object.
1.2 self.student.delegate = self
means student object's delegate will points to teacher object
From main method when [student studentInfo] will be called
2.1 [self.delegate respondToSelector:#selector(teacherName)]
Here delegate already points to teacher object so it can invoke
'teacherName' instance method.
2.2 so [self.delegate performSelector:#selector(teacherName)]
will execute easily.
It looks like Teacher object assign delegate to student object to call it's own method.
It is a relative idea, where we see that student object called 'teacherName' method but it is basically done by teacher object itself.
Please! check below simple step by step tutorial to understand how Delegates works in iOS.
Delegate in iOS
I have created two ViewControllers (for sending data from one to another)
FirstViewController implement delegate (which provides data).
SecondViewController declare the delegate (which will receive data).
Here is the sample code may help you.
AppDelegate.h
#import <UIKit/UIKit.h>
#class FirstViewController;
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) FirstViewController *firstViewController;
#end
AppDelegate.m
#import "AppDelegate.h"
#import "FirstViewController.h"
#implementation AppDelegate
#synthesize firstViewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
//create instance of FirstViewController
firstViewController = [[FirstViewController alloc] init];
//create UINavigationController instance using firstViewController
UINavigationController *firstView = [[UINavigationController alloc] initWithRootViewController:firstViewController];
//added navigation controller to window as a rootViewController
self.window.rootViewController = firstView;
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
#end
FirstViewController.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
#interface FirstViewController : UIViewController<MyDelegate>
#property (nonatomic, retain) NSString *mesasgeData;
#property (weak, nonatomic) IBOutlet UITextField *textField;
#property (weak, nonatomic) IBOutlet UIButton *nextButton;
- (IBAction)buttonPressed:(id)sender;
#property (nonatomic, strong) SecondViewController *secondViewController;
#end
FirstViewController.m
#import "FirstViewController.h"
#interface FirstViewController ()
#end
#implementation FirstViewController
#synthesize mesasgeData;
#synthesize textField;
#synthesize secondViewController;
#pragma mark - View Controller's Life Cycle methods
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Button Click event handling method
- (IBAction)buttonPressed:(id)sender {
//get the input data from text feild and store into string
mesasgeData = textField.text;
//go keypad back when button clicked from textfield
[textField resignFirstResponder];
//crating instance of second view controller
secondViewController = [[SecondViewController alloc]init];
//it says SecondViewController is implementing MyDelegate
secondViewController.myDelegate = self;
//loading new view via navigation controller
[self.navigationController pushViewController:secondViewController animated:YES];
}
#pragma mark - MyDelegate's method implementation
-(NSString *) getMessageString{
return mesasgeData;
}
#end
SecondViewController.h
//declare our own delegate
#protocol MyDelegate <NSObject>
-(NSString *) getMessageString;
#end
#import <UIKit/UIKit.h>
#interface SecondViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *messageLabel;
#property (nonatomic, retain) id <MyDelegate> myDelegate;
#end
SecondViewController.m
#import "SecondViewController.h"
#interface SecondViewController ()
#end
#implementation SecondViewController
#synthesize messageLabel;
#synthesize myDelegate;
- (void)viewDidLoad
{
[super viewDidLoad];
messageLabel.text = [myDelegate getMessageString];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
The delegate fires the automatic events in Objects C. If you set the delegate to Object, it sends the message to another object through the delegate methods.
It's a way to modify the behavior of a class without requiring subclassing.
Each Objects having the delegate methods.These delegate methods fires, when the particular Objects take part in user interaction and Program flow cycle.
Simply stated: delegation is a way of allowing objects to interact with each other without creating strong interdependencies between them.
A delegate captures the taping actions of an user and performs particular Action according to the user Taping Action.
Delegate is nothing but instance of Object which we can call methods behalf of that Objects. and also helps to create methods in rumtime of that Objects.