Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a UIAlertView in NSObject Class

I'm building a login system within my app that will be called several times. So instead of copying and pasting the code into several spots, I'm of course making an NSObject class so I can call the class when needed, instead.

The login system will display a UIAlertView, and when "OK" is tapped, the system will attempt to log in. I can call the class and the UIAlertView will show, but I cannot tell which buttons are tapped. Here is my code:

//Calling the login system

Login *login = [[Login alloc] init];

Login.h:

#import <Foundation/Foundation.h>

@interface Login : NSObject <UIAlertViewDelegate> {

}

@end

Login.m:

#import "Login.h"

@implementation Login

+(void)initialize {

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Login" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];

    [alert show];
    [alert release];

    NSLog(@"Testing");

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex  {

    NSLog(@"Here");

    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];  

    if([title isEqualToString:@"OK"]) {

        NSLog(@"Tapped");

    }

}

@end

For now, before I put UITextFields in the view, I just want to get the app to know which button was tapped. Testing appears in the log, but neither Here nor Tapped appear. Thanks!

like image 785
Jack Humphries Avatar asked Nov 14 '22 07:11

Jack Humphries


1 Answers

Your alert view should not be called by the class method +(void)initialize but by the instance -(id)init method that's why your instance doesn't get the notifications.

the class method "+(void)initialize" is called when the class first load.

the instance method "-(id)init" has its name beginning by init, and is called when you create (instantiate) your object.

-(id)init {

    //alert view

    self = [super init];

    return self;

}
like image 187
moxy Avatar answered Nov 16 '22 04:11

moxy