Tag Archives: Objective-c

Singelton activity indicator class for IPhone

Would it not be nice to have a activity indicator (the spinning busy ‘wheel’) to just throw in wherever you want in an IPhone app? I think so too, so I compiled a singleton activity indicator class to use in my apps.

ActivityIndicator.h

#import <Foundation/Foundation.h>

@interface ActivityIndicator : UIAlertView {
	UIActivityIndicatorView *activityView;
}

@property (nonatomic, retain) UIActivityIndicatorView *activityView;

- (void) close;
+ (id)sharedManager;

@end

ActivityIndicator.m

#import "ActivityIndicator.h"

static ActivityIndicator *sharedManager = nil;

@implementation ActivityAlertView

@synthesize activityView;

#pragma mark -
#pragma mark Singleton Methods

+ (id)sharedManager {

    @synchronized(self) {
        if(sharedManager == nil)
            sharedManager = [[super allocWithZone:NULL] init];
    }
    return sharedManager;
}

+ (id)allocWithZone:(NSZone *)zone {
    return [[self sharedManager] retain];
}

- (id)copyWithZone:(NSZone *)zone {
    return self;
}

- (id)retain {
    return self;
}

- (unsigned)retainCount {
    return UINT_MAX;
}

- (void)release {
    // a singleton should never be release
}

- (id)autorelease {
    return self;
}

#pragma mark -
#pragma mark Init Methods

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        self.activityView = [[UIActivityIndicatorView alloc]
             initWithFrame:CGRectMake(125, 80, 30, 30)];

	    [self addSubview:activityView];

	    activityView.activityIndicatorViewStyle =
            UIActivityIndicatorViewStyleWhiteLarge;

	    [activityView startAnimating];
    }
    return self;
}

#pragma mark -
#pragma mark My Methods

- (void) close {
	[self dismissWithClickedButtonIndex:0 animated:YES];
}

#pragma mark -
#pragma mark Memory Methods

- (void) dealoc {
	[activityView release];
	[super dealloc];
}
@end

Usage:
Initialize and show:

#import "ActivityIndicator.h"

ActivityIndicator *activityIndicator =
     [[[ActivityIndicator sharedManager]
         initWithTitle:@"Fetching highscores"
		 message:@"Please wait..."
		 delegate:self cancelButtonTitle:nil
		 otherButtonTitles:nil] autorelease];

// Show indicator
[activityIndicator show];

Stop/hide activity indicator in another object:

#import "ActivityIndicator.h"

//Get singleton instance
ActivityIndicator *activityIndicator =
     [ActivityIndicator sharedManager];

//Close activity indicator
[activityIndicator close];