A little bit complicated releasing issue for my custom alert view having UITextField - iphone

I know the ARC in iOS 5 but I'm now developing pre-iOS 5 code style, and want to solve this problem by a manual release approach.
My only goal for this is to make a very handy custom alert view with UITextField.
I have a 'BigView' view that has many functions in it. And it can possibly generate many UIAlertView for many different situation on the display with that view. So I know the way use UIAlertViewDelegate for each alert view, but kind of experimentally try want to make this as like UIButton's 'addTarget'(actually it's UIControl's method).
Briefly,
This is in the part of 'BigView' class and my 'TextAlert' instance fired by a button for email gathering .
BigView.m
- (void)emailFeedback:(id)sender
{
TextAlert *textAlert = [[TextAlert alloc] initWithTitle:#"Enter your email address"];
[textAlert setTarget:self action:#selector(textAlertInputed:)];
// [textAlert release];
}
- (void)textAlertInputed:(NSString *)text
{
NSLog(#"text alert inputed, text: %#", text);
}
and these are full my TextAlert files.
TextAlert.h
#import <Foundation/Foundation.h>
#interface TextAlert : NSObject <UIAlertViewDelegate>
{
UIAlertView *alertView;
UITextField *textField;
id target;
SEL action;
}
- (id)initWithTitle:(NSString *)title;
- (void)setTarget:(id)target action:(SEL)action;
#end
TextAlert.m
#import "TextAlert.h"
#implementation TextAlert
- (id)initWithTitle:(NSString *)title
{
if (self = [super init])
{
alertView = [[UIAlertView alloc] initWithTitle:title message:#"beneath" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
textField = [[UITextField alloc] initWithFrame:CGRectMake(12, 45, 260, 25)];
CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0, 60);
[alertView setTransform:myTransform];
[textField setBackgroundColor:[UIColor whiteColor]];
[alertView addSubview:textField];
[alertView show];
}
return self;
}
- (void)dealloc
{
[alertView release]; alertView = nil;
[textField release]; textField = nil;
[super dealloc];
}
- (void)setTarget:(id)_target action:(SEL)_action
{
target = _target;
action = _action;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
[target performSelector:action withObject:textField.text];
}
#end
So my main problem is the releasing point of TextAlert instance in the 'BigView' as you can see the only comment part full codes above. Of course if I remove that comment out, I got crash for call for method of deallocated.
And I also get error make textAlert instance as autoreleased one.
For me, the only solution for this is to make the 'textAlert' object in the 'BigView' a member of 'BigView' not local object. But in that case, my initial goal for handy and lightweight approach for this is not satisfied, I think. And the 'BigView' has already many member instances so I don't want to add any more.
So any suggestions? Or It will be welcome any comment for this trying. I'm ready to hear any
reproves to my insufficient code, really.
Thanks in advance,
MK

If everything works except your release problem you should only consider implementing public "show" method and private "dismiss" method (in your custom alert view).. In show method you should call [self retain] beside other things and on dismiss (add this target to button or whatever dismisses your view) call [self relese].

This isn't directly what you asked for, but could help you anyway.
Handling multiple UIAlertViews in a single UIViewController can be painful. When I ran into this problem, I found an alternative control on github, called BlockAlertsAndActionSheets. It uses blocks instead of delegates, the appearance can be fully customized (even to the default Apple-style) and there is also an "AlertView with an UITextField". Works good for me and I didn't have to reinvent that wheel! ;-)

Related

How to dimiss a UIAlertView when tapping anywhere on the window

I am opening alert popup on click button which is working fine the code is
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"PopUP Title"
message:#"This is pop up window/ Alert"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
UIImageView *tempImageView=[[UIImageView alloc]initWithFrame:CGRectMake(20,20,50,50)];
tempImageView.image=[UIImage imageNamed:#"abc.png"];
[alert addSubView:tempImageView]
[alert show];
the alert box is closing on click of Ok button ,i don't want it, i wants to colse the alert box on click of any where on window .
please help me.
It sounds like you are essentially trying to recreate a "Toast" on iOS. Good news, someone has already done that. See this project.
Edit: Don't want to use iToast. I like your style, less code it is. Here is what I come up with. It would seem obvious as others have said that the only way to overcome the modal nature of the UIAlertView is to add a superview to handle touch events. But you don't have to do that manually every time, consider subclassing UIAlertView. Try something like this:
Edit: #wagashi, Thanks for accepting my answer, and thanks for the heads up about setFrame: being a good place to adjust the size. Your code does make a very toast-like little alert, however when I tried it I found that if the message was to long the view seemed to fall apart. So I have modified setFrame: to simply reduce the size of the alert by about the size of one button, and to remain centered on the screen. So that the class accurately answers the question title "iOS How to dismiss UIAlertView with one tap anywhere?"
NoButtonAlertView.h
#import <UIKit/UIKit.h>
#interface _NoButtonAlertViewCover : UIView
#property (nonatomic,assign) UIAlertView *delegate;
#end
#interface NoButtonAlertView : UIAlertView
-(id)initWithTitle:(NSString *)title message:(NSString *)message;
#end
NoButtonAlertView.m
#import "NoButtonAlertView.h"
#implementation _NoButtonAlertViewCover
#synthesize delegate = _delegate;
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
[self removeFromSuperview];
[_delegate dismissWithClickedButtonIndex:0 animated:YES];
}
#end
#implementation NoButtonAlertView
-(void)show{
[super show];
_NoButtonAlertViewCover *cover = [[_NoButtonAlertViewCover alloc] initWithFrame:[UIScreen mainScreen].bounds];
cover.userInteractionEnabled = YES;
cover.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:.01];
cover.delegate = self;
[self.superview addSubview:cover];
}
-(id)initWithTitle:(NSString *)title message:(NSString *)message{
if ((self = [super initWithTitle:title message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil])){
}
return self;
}
- (void)setFrame:(CGRect)rect {
// Called multiple times, 4 of those times count, so to reduce height by 40
rect.size.height -= 10;
self.center = self.superview.center;
[super setFrame:rect];
}
#end
With this simple UIAlertView subclass and its UIView subclass for a cover, you can use it as simply as you would a standard UIAlertView. Like so:
NoButtonAlertView *alert = [[NoButtonAlertView alloc] initWithTitle:#"Hello" message:#"I am the very model of a modern major general; I'm information, vegitable, animal, and mineral."];
[alert show];
Will yield:

UIActionSheet code crashes when moved from UIViewController file to separate class file

I have searched and searched the board(s) and am not able to figure this out. It has got to be something simple and right in front of me.
I am trying clean up my code and make it more reusable. I was taking some UIActionSheet code that works from a UIViewController and making its own object file. Works fine, until I add UIActionSheetDelegate methods.
When a button is pressed, instead of firing the actionSheetCancel method, it crashes with no stack trace. Every time.
My code is below. Any help would be appreciated. My guess has been it is because I am not using the xcode storyboard tool to connect things together, but I would think this is legal.
egcTestSheet.h:
#import <UIKit/UIKit.h>
#interface egcTestSheet : NSObject <UIActionSheetDelegate> {
}
- (void) showSheet:(UITabBar *) tabBar
displayTitle:(NSString *) name;
#end
egcTestSheet.m
#import "egcTestSheet.h"
#implementation egcTestSheet
-(void) showSheet:(UITabBar *)tabBar displayTitle:(NSString *)name{
UIActionSheet *menu = [[UIActionSheet alloc] initWithTitle:name
delegate:self
cancelButtonTitle:#"Done"
destructiveButtonTitle:#"Cancel"otherButtonTitles:nil];
[menu showFromTabBar:tabBar];
[menu setBounds:CGRectMake(0,0,320, 700)];
}
// actionsheet delegate protocol item
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex: (NSInteger)buttonIndex{
NSLog(#"button index = %d", buttonIndex);
}
- (void)actionSheetCancel:(UIActionSheet *)actionSheet{
NSLog(#"in action canceled method");
}
#end
call code from a UIViewController object:
egcTestSheet *sheet = [[egcTestSheet alloc] init];
[sheet showSheet:self.tabBarController.tabBar displayTitle:#"new test"];
Your action sheet is probably being released as it is dismissed (are you using ARC?). This means when it tries to call it's delegate to inform said delegate of its dismissal/selection, it is trying to call self. Self is a dangling pointer by this time, because it has been released.
In the view controller that is presenting/calling this action sheet, set a property to keep a reference to the action sheet. Set the property to nil on dismissal of the action sheet.

Using UIAlertView in an NSObject

I'm having a terrible time getting a UIAlertView to work within my custom NSObject class. In the research I've done it appears it should be possible but here's what I've run into.
First, here's my code:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
NSLog(#"clickedButtonAtIndex: %d", buttonIndex);
}
-(void)testAlertView {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"List Contains Items"
message:#"List contains items. Remove all items & delete?"
delegate:self
cancelButtonTitle:#"No"
otherButtonTitles:#"Yes", nil];
[alertView show];
}
If I set the delegate to self this code crashes as soon as I tap a button. If I set it to nil clickedButtonAtIndex is never called. I've tried with and without using the <UIAlertViewDelegate>.
I know someone will ask 'why are you doing this in NSObject instead of in your UIViewController?'. Primarily because I want to separate this code out so I can use it from multiple places in my app. But also because this is a small piece of a larger block of logic that makes sense to be on it's own.
Any ideas what I'm doing wrong?
Thanks,
Rich
I had the same problem using ARC. The root of the problem was the same. I solved it by putting my custom NSObject into a "strong" property to make sure the object exists as long as the calling object (an UIVIewCOntroller in my case) exists, so when the delegate of my alert view is called I still have my custom object around and the delegate method works fine.
Add the NSObject as strong property:
#import "Logout.h" // is NSObject
.
.
.
#property (nonatomic, strong) Logout *logout;
Then you will get the delegatemethods called in your NSObject.
Don´t forget to register the delegate for the UIAlertView:
#interface Logout () <UIAlertViewDelegate>
and in your method:
UIAlertView *a = [[UIAlertView alloc] initWithTitle:#"title"
message:#"message" delegate:self cancelButtonTitle:#"cancel"
otherButtonTitles:#"ok", nil];
[a show];
How To Present An Alert View Using UIAlertController When You Don't Have A View Controller. Detail description.
Yes, you can only use UIAlertController only in UIViewController classes. So how can we do it in NSObject classes. If you see the description link given above you will get to the answer. To summarise in a line for the above description: Create a new window above the the current window. This new window will be our viewController where we display alert. So using this viewController you can call the method [presentViewController: animated: completion:].
Answer:
dispatch_async(dispatch_get_main_queue(), ^{
UIWindow* window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
window.rootViewController = [UIViewController new];
window.windowLevel = UIWindowLevelAlert + 1;
NSString *msg=#“Your mssg";
UIAlertController* alertCtrl = [UIAlertController alertControllerWithTitle:#“Title" message:msg preferredStyle:UIAlertControllerStyleAlert];
[alertCtrl addAction:[UIAlertAction actionWithTitle:NSLocalizedString(#"Yes",#"Generic confirm") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
// do your stuff
// very important to hide the window afterwards.
window.hidden = YES;
}]];
UIAlertAction *cancelAction= [UIAlertAction actionWithTitle:#"cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
window.hidden = YES;
}];
[alertCtrl addAction:cancelAction];
//http://stackoverflow.com/questions/25260290/makekeywindow-vs-makekeyandvisible
[window makeKeyAndVisible]; //The makeKeyAndVisible message makes a window key, and moves it to be in front of any other windows on its level
[window.rootViewController presentViewController:alertCtrl animated:YES completion:nil];
});

Get immediate value from UIALertView

I have what can be most accurately described as a Factory, which is generating some NSOperations. Before the NSOPerations are generated, I would like to check the current network status and, if the user is on a 3G/Mobile connection, warn them that they are about to do a data-heavy operation.
I attempted to do this with a UIAlertView, but the only way I can see to get the "response" from a UIAlertView is via the event-based delegate system. I was wondering if there was any way to have it act like the "confirm" dialogue in JavaScript, where it blocks the UI and I can get an immediate value from it once it is dismissed.
Is there any standard way to do this, or some example code I could be pointed towards that accomplishes something similar?
Blocking the main thread is considered bad practice on iOS, and thus there is no synchronous API for UIAlertView.
You should implement a delegate callback for the alert that enqueues the relevant NSOperation. It may be useful to subclass UIAlertView to store the relevant data you need to enqueue the NSOperation, or better yet store a block that captures the relevant variables and then just execute that when the user confirms the dialog.
You can implement something similar to that, using blocks. The execution will continue as in all other cases, but the flow of reading your code might more resemble what you want. Here is a helper class that I made for that purpose so that I can just go:
[YUYesNoListener yesNoWithTitle:#"My Title" message:#"My Message" yesBlock:^
{
NSLog(#"YES PRESSED!");
}
noBlock:^
{
NSLog(#"NO PRESSED!");
}];
...and here is the helper class:
typedef void(^EmptyBlockType)();
#interface YUYesNoListener : NSObject <UIAlertViewDelegate>
#property (nonatomic, retain) EmptyBlockType yesBlock;
#property (nonatomic, retain) EmptyBlockType noBlock;
+ (void) yesNoWithTitle:(NSString*)title message:(NSString*)message yesBlock:(EmptyBlockType)yesBlock noBlock:(EmptyBlockType)noBlock;
#end
#implementation YUYesNoListener
#synthesize yesBlock = _yesBlock;
#synthesize noBlock = _noBlock;
- (id) initWithYesBlock:(EmptyBlockType)yesBlock noBlock:(EmptyBlockType)noBlock
{
self = [super init];
if (self)
{
self.yesBlock = [[yesBlock copy] autorelease];
self.noBlock = [[noBlock copy] autorelease];
}
return self;
}
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0 && self.noBlock)
self.noBlock();
else if (buttonIndex == 1 && self.yesBlock)
self.yesBlock();
[_yesBlock release];
[_noBlock release];
[alertView release];
[self release];
}
- (void) alertViewCancel:(UIAlertView *)alertView
{
if (self.noBlock)
self.noBlock();
[_yesBlock release];
[_noBlock release];
[alertView release];
[self release];
}
+ (void) yesNoWithTitle:(NSString*)title message:(NSString*)message yesBlock:(EmptyBlockType)yesBlock noBlock:(EmptyBlockType)noBlock
{
YUYesNoListener* yesNoListener = [[YUYesNoListener alloc] initWithYesBlock:yesBlock noBlock:noBlock];
[[[UIAlertView alloc] initWithTitle:title message:message delegate:yesNoListener cancelButtonTitle:#"No" otherButtonTitles:#"Yes", nil] show];
}
#end
Using the code of Ricky Helgesson, I've built a Pod component to use this solution easily in any project that uses CocoaPods.
https://github.com/nmaletm/STAlertView
The code that you should use is:
[[STAlertView alloc] initWithTitle:#"Title of the alert"
message:#"Message you want to show"
cancelButtonTitle:#"No" otherButtonTitles:#"Yes"
cancelButtonBlock:^{
// Code todo when the user cancel
...
} otherButtonBlock:^{
// Code todo when the user accept
...
}];
And add at the Podfile:
pod "STAlertView"
There are more instructions at the github page.

Using OCUnit to test if an UIAlertView is presented

I'm working on an app that will display a UIAlertView upon hitting it's exit button, only if progress in the game has been made. I was wondering how you would use OCUnit to intercept the UIAlertView and interact with it, or even detect if it has been presented. The only thing I can think of is to monkeypatch [UIAlertViewDelegate willPresentAlertView], but that makes me want to cry.
Does anyone know of a better method of doing this?
Update: See my blog post How to Unit Test Your Alerts and Action Sheets
The problem with my other answer is that the -showAlertWithMessage: method itself is never exercised by unit tests. "Use manual testing to verify it once" isn't too bad for easy scenarios, but error handling often involves unusual situations that are difficult to reproduce. …Besides, I got that nagging feeling that I had stopped short, and that there might be a more thorough way. There is.
In the class under test, don't instantiate UIAlertView directly. Instead, define a method
+ (Class)alertViewClass
{
return [UIAlertView class];
}
that can be replaced using "subclass and override." (Alternatively, use dependency injection and pass this class in as an initializer argument.)
Invoke this to determine the class to instantiate to show an alert:
Class alertViewClass = [[self class] alertViewClass];
id alert = [[alertViewClass alloc] initWithTitle:...etc...
Now define a mock alert view class. Its job is to remember its initializer arguments, and post a notification, passing itself as the object:
- (void)show
{
[[NSNotificationCenter defaultCenter] postNotificationName:MockAlertViewShowNotification
object:self
userInfo:nil];
}
Your testing subclass (TestingFoo) redefines +alertViewClass to substitute the mock:
+ (Class)alertViewClass
{
return [MockAlertView class];
}
Make your test class register for the notification. The invoked method can now verify the arguments passed to the alert initializer and the number of times -show was messaged.
Additional tip: In addition to the mock alert, I defined an alert verifier class that:
Registers for the notification
Lets me set expected values
Upon notification, verifies the state against the expected values
So all my alert tests do now is create the verifier, set the expectations, and exercise the call.
The latest version of OCMock (2.2.1 the at time of this writing) has features that make this easy. Here's some sample test code that stubs UIAlertView's "alloc" class method to return a mock object instead of a real UIAlertView.
id mockAlertView = [OCMockObject mockForClass:[UIAlertView class]];
[[[mockAlertView stub] andReturn:mockAlertView] alloc];
(void)[[[mockAlertView expect] andReturn:mockAlertView]
initWithTitle:OCMOCK_ANY
message:OCMOCK_ANY
delegate:OCMOCK_ANY
cancelButtonTitle:OCMOCK_ANY
otherButtonTitles:OCMOCK_ANY, nil];
[[mockAlertView expect] show];
[myViewController doSomething];
[mockAlertView verify];
Note: Please see my other answer. I recommend it over this one.
In the actual class, define a short method to show an alert, something like:
- (void)showAlertWithMessage:(NSString message *)message
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
message:message
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
For your test, don't test this actual method. Instead, use "subclass and override" to define a spy that simply records its calls and arguments. Let's say the original class is named "Foo". Here's a subclass for testing purposes:
#interface TestingFoo : Foo
#property(nonatomic, assign) NSUInteger countShowAlert;
#property(nonatomic, retain) NSString *lastShowAlertMessage;
#end
#implementation TestingFoo
#synthesize countShowAlert;
#synthesize lastShowAlertMessage;
- (void)dealloc
{
[lastShowAlertMessage release];
[super dealloc];
}
- (void)showAlertWithMessage:(NSString message *)message
{
++countShowAlert;
[self setLastShowAlertMessage:message];
}
#end
Now as long as
your code calls -showAlertWithMessage: instead of showing an alert directly, and
your test code instantiates TestingFoo instead of Foo,
you can check the number of calls to show an alert, and the last message.
Since this doesn't exercise the actual code that shows an alert, use manual testing to verify it once.
You can get unit tests for alert views fairly seamlessly by exchanging the 'show' implementation of UIAlertView. For example, this interface gives you some amount of testing abilities:
#interface UIAlertView (Testing)
+ (void)skipNext;
+ (BOOL)didSkip;
#end
with this implementation
#import <objc/runtime.h>
#implementation UIAlertView (Testing)
static BOOL skip = NO;
+ (id)alloc
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method showMethod = class_getInstanceMethod(self, #selector(show));
Method show_Method = class_getInstanceMethod(self, #selector(show_));
method_exchangeImplementations(showMethod, show_Method);
});
return [super alloc];
}
+ (void)skipNext
{
skip = YES;
}
+ (BOOL)didSkip
{
return !skip;
}
- (void)show_
{
NSLog(#"UIAlertView :: would appear here (%#) [ title = %#; message = %# ]", skip ? #"predicted" : #"unexpected", [self title], [self message]);
if (skip) {
skip = NO;
return;
}
}
#end
You can write unit tests e.g. like this:
[UIAlertView skipNext];
// do something that you expect will give an alert
STAssertTrue([UIAlertView didSkip], #"Alert view did not appear as expected");
If you want to automate tapping a specific button in the alert view, you will need some more magic. The interface gets two new class methods:
#interface UIAlertView (Testing)
+ (void)skipNext;
+ (BOOL)didSkip;
+ (void)tapNext:(NSString *)buttonTitle;
+ (BOOL)didTap;
#end
which go like this
static NSString *next = nil;
+ (void)tapNext:(NSString *)buttonTitle
{
[next release];
next = [buttonTitle retain];
}
+ (BOOL)didTap
{
BOOL result = !next;
[next release];
next = nil;
return result;
}
and the show method becomes
- (void)show_
{
if (next) {
NSLog(#"UIAlertView :: simulating alert for tapping %#", next);
for (NSInteger i = 0; i < [self numberOfButtons]; i++)
if ([next isEqualToString:[self buttonTitleAtIndex:i]]) {
[next release];
next = nil;
[self alertView:self clickedButtonAtIndex:i];
return;
}
return;
}
NSLog(#"UIAlertView :: would appear here (%#) [ title = %#; message = %# ]", skip ? #"predicted" : #"unexpected", [self title], [self message]);
if (skip) {
skip = NO;
return;
}
}
This can be tested similarly, but instead of skipNext you'd say which button to tap. E.g.
[UIAlertView tapNext:#"Download"];
// do stuff that triggers an alert view with a "Download" button among others
STAssertTrue([UIAlertView didTap], #"Download was never tappable or never tapped");