2013-10-08 63 views
1

我刚开始开发iOS应用程序,而英语不是我的母语,所以请原谅任何错误和难看的代码。iOS应用程序:应在特定日期显示特定图像,但崩溃

我试图创建的应用程序应该只在特定的一天显示一个特定的图像(如果日期发生变化,则更改图像)。 因此我实现了一个无限循环,其中检查日期。如果它与最后一次更改图像不同,则图像会再次更改。图像以“YearMonthDay.png”程序命名(例如“20131017.png”)。

我已经GOOGLE了很多,并得到了一些代码(我知道这是非常丑陋的),但它每次崩溃。

我真的很感激任何帮助!

smViewController.h:

#import <UIKit/UIKit.h> 

@interface smViewController : UIViewController { 
    UIImageView* mImageView; 
} 

@property (nonatomic, retain) IBOutlet UIImageView* imageView; 

- (IBAction)contentModeChanged:(UISegmentedControl*)segmentedControl; 

@end 

smViewController.m

#import "smViewController.h" 

@interface smViewController() 

@end 

@implementation smViewController 
@synthesize imageView = mImageView; 

- (void)viewDidUnload 
{ 
    self.imageView = nil; 
    [super viewDidUnload]; 
} 

- (void)dealloc 
{ 
    [mImageView release]; 
    [super dealloc]; 
} 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    NSString *oldDateString = @""; 

    while(true) 
    { 
     NSDate *today = [NSDate date]; 
     NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
     [dateFormat setDateFormat:@"yyyy/MM/dd"]; 
     NSString *dateString = [dateFormat stringFromDate:today]; 
     NSLog(@"date: %@", dateString); 
     if([dateString isEqualToString: oldDateString]) 
     { 
     } 
     else 
     { 
      NSAssert(self.imageView, @"self.imageView is nil. Check your IBOutlet connections"); 
      UIImage* image = [UIImage imageNamed:dateString]; 
      NSAssert(image, @"image is nil. Check that you added the image to your bundle and that the filename above matches the name of you image."); 
      self.imageView.backgroundColor = [UIColor whiteColor]; 
      self.imageView.clipsToBounds = YES; 
      self.imageView.image = image; 
      oldDateString = dateString; 
     } 
     [dateFormat release]; 
    } 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

@end 
+0

它在哪里崩溃? – Larme

+2

你的'while(true)'循环会阻塞主线程并处理所有的事件处理(并且处理器时间为100%)。你必须了解计时器... –

回答

0

可能是因为while循环。它阻止了你的应用程序。

您应该使用定时器来代替,这样的事情:

NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkDate) userInfo:nil repeats:YES]; 
[timer fire]; 

如果您要检查的新日期,每1秒(你可能会被罚款更高的频率)和checkDate是方法,你检查日期并根据需要更换图像。

1

你应该重写 - (void)applicationSignificantTimeChange:(UIApplication *)应用程序在你的应用UIApplicationDelegate。然后当日期发生变化时您将收到一个事件,您可以删除任何循环或计时器。

+0

哦!我喜欢这个比我的回答更好。 – Odrakir

相关问题