'UITabbarController'에 해당되는 글 1건

  1. 2011.07.18 [iphone] UITabbarController에서 탭을 선택했을때 항상 Reload, Refresh하기
iPhone App2011. 7. 18. 13:39

샘플로 칼로리 계산기를 만들면서 Tab을 클릭하면 항상 새로운 데이터를 다시 로드하는 것을 하고 싶었다.

인터넷 찾아보니

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {

NSLog(@"didSelectViewController : %@",viewController);

}


이런 delegate를 사용하란다. 이것을 호출하기 위해서 헤더에 프로토콜을 추가하고 이렇게

interface CalrorieCalAppDelegate : NSObject <UIApplicationDelegate,UITabBarControllerDelegate> {


IBOutlet UITabBarController *tabBar;

}


이 delegate를 꼭 추가해준다 구현부에
[self.tabBar setDelegate:self];
추가한 곳은 아래와 같다.    

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

// Override point for customization after application launch.

//self.window.rootViewController = self.viewController;

self.window.rootViewController = self.tabBar;

[self.tabBar setDelegate:self];

[self.window makeKeyAndVisible];

return YES;

}



하지만 이것보다 더 좋은 방법이 있다. 바로


-(void) viewWillAppear:(BOOL)animated


이걸 이용한 방법이다. view에서 override 해서 쓴다.

tab을 읽기전에 항상 호출된다.


자 이곳에서 refresh를 해주자.


-(void) viewWillAppear:(BOOL)animated

{

AteFoodData* afd = [AteFoodData sharedSingletonClass];

count = [[NSNumber alloc] init];

NSMutableString *totalName = [NSMutableString stringWithString:@"음식 이름\n\n"];

for(NSArray *item in afd.foodData)

{

NSNumber *calrorie = [NSNumber numberWithInt:[[item objectForKey:@"calrorie"] intValue]];

count = [NSNumber numberWithInt:[count intValue]+[calrorie intValue]];

NSString *name = [NSString stringWithString:[item objectForKey:@"name"]];

[totalName appendFormat:@"%@ (%d) Cal \n",name,[calrorie intValue]];

}

  

resultTextView.text = [NSString stringWithFormat:totalName];

resultLabel.text = [NSString stringWithFormat:@"당신이 섭취한 칼로리는? (%d칼로리)",[count intValue]];

}


이렇게 하면 탭을 눌렀을때 항상 값을 읽어온다.
여담이지만 여기서 메모리 에러가 나서 고생했었는데 count를 전역변수로 해서 쓰는데 header에서 NSNumber로 해서정의했지만
count = [[NSNumber alloc] init];

이렇게 count를 초기화를 안해줘서 메모리 에러가 났었다. 항상 초기화를 해주자.!!






Posted by 동동(이재동)