UITableViewでfizzbuzz

UITableViewの追加、dataSourceとdelegateをfizzbuzzAppDelegateに繋ぐのはInterfaceBuilder側で行う。

ヘッダファイル。

#import <UIKit/UIKit.h>

@interface fizzbuzzAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
	UITableViewController *tvc;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UITableViewController *tvc;

-(NSString *)fizzbuzz:(NSUInteger *)n;

@end

実装ファイル

#import "fizzbuzzAppDelegate.h"

@implementation fizzbuzzAppDelegate

@synthesize window;
@synthesize tvc;

- (void)applicationDidFinishLaunching:(UIApplication *)application {    

    // Override point for customization after application launch
    [window makeKeyAndVisible];
}


- (void)dealloc {
    [tvc release];
    [window release];
    [super dealloc];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
	return 1;
}


- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
	return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	// fizzbuzz
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
	if(cell == nil){
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"] autorelease];
	}
	cell.text = [self fizzbuzz:indexPath.row];
	return cell;
}

-(NSString *)fizzbuzz:(NSUInteger *)n
{
	NSMutableString *str = [NSMutableString string];
	int k = (int)n + 1;
	NSLog(@"num : %d",k);
	if(k % 3 == 0){
		[str appendString:@"fizz"];
	}
	if(k % 5 == 0){
		[str appendString:@"buzz"];
	}
	if([str length] == 0){
		[str appendFormat:@"%d",k];
	}
	return str;
}
@end

スクロールしていくと、100までのfizzbuzzを順に表示する。
こんな感じ

も、もうええやろwwww < fizzbuzz


ところで、UITableViewCellのプロパティtextに文字列を代入する方法は推奨されていないらしい。
となると、UITableViewCellのサブクラスを作成して、、、とするしかないのかな??