Jack Humphries
Jack Humphries

Reputation: 13267

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!

Upvotes: 5

Views: 3933

Answers (4)

SathishKumarEro
SathishKumarEro

Reputation: 87

It's Simple :

Create a property for your NSObject class in your view controller class :

in h file :

@property (nonatomic , retain) LoginCheckNSObject *LoginCheckerObject;

in m file :

self.LoginCheckerObject=[[LoginCheckNSObject alloc] init];
[self.LoginCheckerObject setDelegate:self];
[self.LoginCheckerObject TrackNowLogin];

Upvotes: 0

moxy
moxy

Reputation: 1624

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;

}

Upvotes: 1

Phillip Mills
Phillip Mills

Reputation: 31026

When you use self in a class method you're referring to the class itself, rather than an instance of the class. However, your delegate method is an instance method. You probably want the caller to create a Login instance and have the instance create the alert, plus be its delegate.

Upvotes: 0

beryllium
beryllium

Reputation: 29767

Just

switch(buttonIndex){
    case 0:
        NSLog(@"Tapped First Button");
        break;
    case 1:
        break;
    default:
        break;
}

Upvotes: 0

Related Questions