As I understood, I should not be retaining a controller which is a delegate or datasource. I have made a UIPickerView, created in a property accessor as such:
-(UIPickerView *)projectPicker {
if (_projectPicker != nil) {
return _projectPicker;
}
//Create Picker View
UIPickerView *picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 185, 0, 0)];
picker.showsSelectionIndicator = YES;
//Create source and delegate
NSString *titleForRow0 = NSLocalizedString(#"<<Make Selection>>", #"projectPicker nil Label 0");
NSArray *titlesForFirstRows = [[NSArray alloc] initWithObjects:titleForRow0, nil];
ProjectPickerDatasource *pickerSource = [[ProjectPickerDatasource alloc] initWithManagedObjectContext:self.managedObjectContext
selectedProject:self.currentProject
andTitlesForFirstRows:titlesForFirstRows];
[titlesForFirstRows release];
picker.delegate = pickerSource;
picker.dataSource = pickerSource;
self.projectPicker = picker;
[pickerSource release];
[picker release];
return _projectPicker;
}
This crashes reporting an attempt to access an unallocated instance of pickerSource.
If I break the pickerSource component out as another property, thereby retaining it within this controller, it works perfectly.
I did not think that was the proper implementation. Doesn't the pickerView retain it's delegate and datasource until it is destroyed?
If the Picker instantiates the datasource it is fine to retain it, it needs to be retained somewhere. Just be sure to release it.
Note, datasources are handled differently that delegates.
Mostly (as for as I know) the delegates are not retained by their classes. They are just assigned like this,
#property(nonatomic, assign) id <TheDelegateClass> delegate;
Its the responsibility of the caller to retain the delegate until the delegates job is over.
The answer for your question is UIPickerView doesn't retain its delegate. It expects you to retain it instead.
Related
Please see attached image for reference. All of the viewControllers have been already removed from the app but Memory Debugger shows its instances as well as all its properties. When i click the Show Only Leaked blocks filter of Memory Debugger, the viewControllers and other instances do not appear in it. Does it mean there are no leaks?
How do I solve the problem. What does it mean?
I do have the PKYStepper block in the CartViewController's cellForRowAtIndexPath (Stepper is a UIControl in my TableViewCell) method as follows :
PKYStepper *qtyStepper = [cell viewWithTag:993];
qtyStepper.tappedCallback = ^(PKYStepper *stepper) {
NSLog(#"Tapped!");
rowSelected = indexPath;
if (((Dish*)((MenuSubSection*)_section.subSections[0]).dishesArray[indexPath.row]).disheOptions.count)
{
UIWindow *window = [UIApplication sharedApplication].keyWindow;
NSBundle* bun = [NSBundle bundleWithIdentifier:#"com.test.test"];
DishItemOption *dishOptions = [[bun loadNibNamed:#"DishItemOption" owner:self options:nil] objectAtIndex:0];
dishOptions.frame = CGRectMake(0, 0, window.frame.size.width, window.frame.size.height);
dishOptions.dish = [[Dish alloc] initWithDishObject:((Dish*)((MenuSubSection*)_section.subSections[0]).dishesArray[indexPath.row])];
dishOptions.delegate = self;
[window addSubview:dishOptions];
}
};
How to make it reference the Weak Self?
It looks like you've likely captured the view controller in a callback block of some sort.
Specifically, PKYStepper seems to have a callback block that is strongly referencing the view controller. Either make sure said reference is weak or make sure the block is properly destroyed when the view controller is torn down.
Found the solution. Updated my callbacks to the following :
__weak typeof(self) weakSelf = self;
qtyStepper.incrementCallback = ^(PKYStepper *stepper, float newValue) {
CartViewController *sSelf = weakSelf;
[sSelf updateTotalCharges]; //Had to use WEAKSELF in the callback!
};
I've wrote a class which gets an image from the camera. Its header is as follows:
typedef void(^ImageTakenCallback)(UIImage *image);
#interface ImageGetter : NSObject <UIImagePickerControllerDelegate, UIPopoverControllerDelegate>
{
UIImagePickerController *picker;
ImageTakenCallback completionBlock
}
-(void) requestImageInView:(UIView*)view withCompletionBlock:(void(^)(UIImage*))completion;
#end
As you can see, I'm trying to make something like that in client code:
[[[ImageGetter alloc] init] requestImageInView:_viewController.view withCompletionBlock:^(UIImage *image) {
// do stuff with taken image
}];
Here is how I've implemented ImageGetter:
-(void) requestImageInView:(UIView*)view withCompletionBlock:(ImageTakenCallback)completion
{
completionBlock = [completion copy];
picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.delegate = self;
[view addSubview:picker.view];
}
- (void)imagePickerController:(UIImagePickerController *)picker_
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
[picker.view removeFromSuperview];
picker = nil;
completionBlock(image);
}
The problem is since I'm using ARC, the instance of ImageGetter is deallocated instantly after call for -requestImage..., so the weak delegate of picker becomes nil.
Which are common ways to resolve such a issue?
I can see some ways, however, none of them seems to be quite right:
retain ImageGetter from client code, for example, assign it to a strong property. The problems here are: I wont be able to release it by setting this property to nil right after I get image, because this will mean setting retain count of object to 0 while executing the method of this object. Also, I don't want unnecessary properties (well, it is not a big problem, but nevertheless).
disable ARC for ImageGetter and manually retain at start itself and release after sending image to callback.
make static manager ImageGetterManager, which will have method requestImage..., it will create ImageGetter instances, retain them, redirect the requestImage... call, get callbacks from them and release. That seems the most consistent way, but is not it a bit complex for such a little code?
So how can I build such a class?
You can handle that within the ImageGetter class by creating and releasing a "self-reference".
In a class extension in the implementation file, declare a property
#interface ImageGetter ()
#property (strong, nonatomic) id selfRef;
#end
In requestImageInView:, set self.selfRef = self to prevent deallocation.
In the completion method, set self.selfRef = nil.
Remark: Actually you can manage the retain count even with ARC:
CFRetain((__bridge CFTypeRef)(self)); // Increases the retain count to prevent deallocation.
CFRelease((__bridge CFTypeRef)(self)); // Decreases the retain count.
But I am not sure if this is considered "good programming" with ARC or not.
Any feedback is welcome!
If this issue is introduced when switching to ARC, I should just go for option 1, and define it as a strong property.
However the behaviour is a bit different than you described for option 1: Setting the property to nil, does NOT mean the object is instantly released, it will just cause a decrement of the retaincount. ARC will handle that fine, the object will be released as soon as all referenced objects have 'released' it.
You can use the following strategy:
ImageGetter* imgGetter = [[ImageGetter alloc] init];
[imgGetter requestImageInView:_viewController.view withCompletionBlock:^(UIImage *image) {
// do stuff with taken image
[imgGetter releaseCompletionBlock]; // With this line, the completion block will retain automatically imgGetter, which will be released after the release of the completionBlock.
}];
Inside your ImageGetter implementation class, create a method that you can call inside the block like this.
-(void) releaseCompletionBlock
{
completionBlock = nil;
}
i am using ARC, my code is as :
-(void)viewAllCustomer:(id)sender
{
if([self.popOver isPopoverVisible])
{
[self.popOver dismissPopoverAnimated:YES];
}
CustomersViewController *allCustomer=[[CustomersViewController alloc]init];
[allCustomer setDelegateAction:self];
[allCustomer.view setFrame:CGRectMake(0, 0, 370, 420)];
UINavigationController *navController=[[UINavigationController alloc]initWithRootViewController:allCustomer];
UIPopoverController *_popOver=[[UIPopoverController alloc]initWithContentViewController:navController];
[_popOver setPassthroughViews:[NSArray arrayWithObject:self]];
[_popOver setPopoverContentSize:CGSizeMake(370, 420)];
UIButton *button=(UIButton *)sender;
// 60.0, 54.0
CGRect buttonFrame=CGRectMake(button.frame.origin.x+25, button.frame.origin.y+35, 10,10);
[_popOver presentPopoverFromRect:buttonFrame inView:self permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
self.popOver=_popOver;//popOver is (nonatomic,retain)
}
i am getting memory leak as:
Thanks.
i my self have to give answer of this question, thanks to #abizern.Actually the leak was due to _var._var is just a different name for the instance variable (presumably so you don't accidentally access directly it when you meant to use an accessor).In the code provided to me was accidentally assigning _var to self.var.
i simply made the #property(nonatomic, retain) and use it as self.var in implementation file.No more memory leaks .Also in arc property are auto synthesise, so no more need to explicitly #synthesise removed.
while going through developer apple i found this:
In this example, it’s clear that myString is a local variable and _someString is an instance variable.
In general, you should use accessor methods or dot syntax for property access even if you’re accessing an object’s properties from within its own implementation, in which case you should use self:
- (void)someMethod {
NSString *myString = #"An interesting string";//my bad was that i have taken _myString
self.someString = myString;//again self.someString = _myString //wrong
// or[self setSomeString:myString];
}
I have a question. There may be a very simple solution to this question but I am not able to figure it out yet. If I use a property say #property(nonatomic, retain)UIView *mainView.
Now I synthesize it in .m file and release it in the dealloc method as following:
- (void)dealloc {
[mainView release], mainView = nil;
[super dealloc];
}
Then in my viewDidLoad, I'm allocating it and adding it as the subview of my self.view like following:
- (void) viewDidLoad {
mainView = [[UIView alloc] init];
.
.
.
[self.view addSubView: mainView];
}
Now I understand that at this point my mainView would have 3 reference counts (one from alloc, one because it's a retained property, and the third one when I added it to self.view), its parent controller would own it too.
Now, my question is if after adding my view to self.view, I release my mainView using
[mainView release];
My app crashes when I go back to the previous view as I am sending release to already deallocated object. Now my question is how am I overreleasing my view here. what am I missing because when I use following code it works fine and no crashes occur.
- (void) viewDidLoad {
UIView *newView = [[UIView alloc] init];
self.mainView = newView;
[newView release];
.
.
.
[self.view addSubView: mainView];
}
I know why this second viewDidLoad method works but what I dont know is why first one fails, I am supposed to release my view after adding it to self.view. Right?
NOTE: I understand that in the first viewDidLoad, I can use autorelease method to release the view that is being assigned to the ivar and it wont crash but the whole point is I am trying to reduce the use of autorelease as much as possible. And I am not using ARC at all
I would really appreciate the explanation and suggestions.
From your question:
Now i understand that at this point my mainView would have 3 reference
counts (one from alloc, one coz its a retained property and the third
one when i added it to self.view)
You didn't assign through the property but assigned directly to the instance variable, so there was no retain; only in ARC does assigning to the instance variable retain the value. So, do not perform the manual release.
In order for your #property to retain the mainView, you should use it as self.mainView and not just mainView. If you use the latter alone, it will not retain it. Basically if you call self.mainView = ... it is calling a setter method for mainView which does a [mainView retain]; internally. When you are directly assigning it, it wont execute this setter and retain will not be executed.
You should try it like this,
self.mainView = [[[UIView alloc] init] autorelease];
[self.view addSubView:self.mainView];
or as shown in your question.
UIView *newView = [UIView alloc] init];
self.mainView = newView;
[newView release];
[self.view addSubView:self.mainView];
You can also try using ARC for your project. Your code will look like this in ARC,
self.mainView = [[UIView alloc] init];
[self.view addSubView:self.mainView];
Check the documentation for more details.
In your first viewDidLoad method you are not referring to self.mainView only mainView thats why its not retained, in order to retain property work you have to set mainView using self.mainView!
I am trying to use the iOS zxing Widget for QR Code Scanning. I have a ViewController which is pushed as an Item in my UINavigationController or presented Modally from another ViewController. This ViewController has a SegmentedControl for 3 different views. Two of those Views are UIWebViews which load simple Websites, nothing special about them.
The selection looks something like this:
- (IBAction)segmentedControlValueChanged:(id)sender {
NSString *urlString;
ZXingWidgetController *widController;
QRCodeReader* qrcodeReader;
NSSet *readers;
switch (segmentedControl.selectedSegmentIndex) {
case 0:
[self.view bringSubviewToFront:self.productSearchWebView];
urlString = [[SACommunicationService sharedCommunicationService] getURLforKey:kURLTypeProductSearch];
[self.productSearchWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
break;
case 1:
[self.view bringSubviewToFront:self.marketSearchWebView];
urlString = [[SACommunicationService sharedCommunicationService] getURLforKey:kURLTypeMarketSearch];
[self.marketSearchWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
break;
case 2:
widController = [[ZXingWidgetController alloc] initWithDelegate:self showCancel:YES OneDMode:NO];
qrcodeReader = [[QRCodeReader alloc] init];
readers = [[NSSet alloc] initWithObjects:qrcodeReader,nil];
widController.readers = readers;
[self.QRCodeScannerView addSubview:widController.view];
[self.view bringSubviewToFront:self.QRCodeScannerView];
break;
default:
break;
}
}
I tried to debug and go step by step and find out where the problem comes from:
Decoder (which is part of the underlying ZXing logic) tries to call "failedToDecodeImage:" from its delegate (which should be the ZXingWidgetController class) and crashes (EXC_BAD_ACCESS)
While stepping through I found out that the "cancelled" Method of the ZXingWidgetController gets called. Now I don't really know why this method gets called. The Widget shouldn't stop right after initializing and starting the decoder.
So the answer is a very simple one.
I was using iOS 5.0 and ARC. The ZXing ViewController is instantiated locally inside the method. Since the ViewController itself does not get viewed ARC sets a release at the end of the method and the ViewController gets freed. Since the ViewController is released, the view which was retained by the ViewController will be released as well. Cancelled is called because the Main ViewController does not exist anymore and calling some method on a nil pointer results in a BAD_ACCESS.
The Solution here was to set the ZXingViewController as a global strong property. This kept the object from being released right at the end of that method and thus the view which was added as a subview to another ViewControllers view was held in memory as long as the ViewController was alive.
You're not supposed to add controller views as subviews of another view. You're suposed to present controllers using the various UIViewController mechanisms.
By doing what you're doing, you're violating UIViewController contracts. The widget isn't getting things like viewWillAppear, viewDidAppear, etc.
If you want to use ZXing at the UIView/CALayer level instead of the UIViewController level, look at the classes in the ZXing objc directory.
Try this... also in the .h file make this ZXingWidgetController *widController;
And also to the viewScanner set clipToBounds to true.
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self performSelector:#selector(openScanner) withObject:nil afterDelay:0.5];
}
-(void)openScanner
{
self.widController = [[ZXingWidgetController alloc] initMiniWithDelegate:self showCancel:NO OneDMode:YES];
NSMutableSet *readers = [[NSMutableSet alloc ] init];
MultiFormatReader* reader = [[MultiFormatReader alloc] init];
[readers addObject:reader];
self.widController.readers = readers;
[viewScanner addSubview:self.widController.view];
}