objective-c随机数+日期格式显示一例

在原来的代码上有修改,主要为:

  1. 将准备随机数方法放到了init中,这样不用手动调用了
  2. setWeek方法已经过时,使用的是setWeekOfYear方法

在此放一份以备以后查找:

le.h

//
// LotteryEntry.h
// lottery
//
// Created by kinds on 15/6/25.
// Copyright (c) 2015年 hopy. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface LotteryEntry : NSObject{
    NSDate *entry_date;
    int first_number;
    int second_number;
}

-(void)prepareRandomNumbers;
-(void)setEntryDate:(NSDate*)date;
-(NSDate *)entryDate;
-(int)firstNumber;
-(int)secondNumber;
@end

le.m

//
// LotteryEntry.m
// lottery
//
// Created by kinds on 15/6/25.
// Copyright (c) 2015年 hopy. All rights reserved.
//

#import "LotteryEntry.h"

@implementation LotteryEntry

-(id)init{
    self = [super init];
    if(self){
        [self prepareRandomNumbers];
    }
    return self;
}

-(void)prepareRandomNumbers{
    first_number = ((int)random()%100) + 1;
    second_number = ((int)random()%100) + 1;
}

-(void)setEntryDate:(NSDate *)date{
    entry_date = date;
}

-(NSDate*)entryDate{
    return entry_date;
}

-(int)firstNumber{
    return first_number;
}

-(int)secondNumber{
    return second_number;
}

-(NSString *)description{
    NSDateFormatter *df = [NSDateFormatter new];
    [df setTimeStyle:NSDateFormatterShortStyle];
    [df setDateStyle:NSDateFormatterMediumStyle];
    return [[NSString alloc]initWithFormat:@"%@ = %d and %d",
            [df stringFromDate:entry_date],first_number,second_number];
}
@end

main.m

//
// main.m
// lottery
//
// Created by kinds on 15/6/24.
// Copyright (c) 2015年 hopy. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "LotteryEntry.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSDate *now = [NSDate new];
        NSCalendar *cal = [NSCalendar currentCalendar];
        NSDateComponents *to_week = [NSDateComponents new];

        srandom((unsigned)time(NULL));
        NSMutableArray *mary = [NSMutableArray new];
        for(int i = 0;i<10;i++){
            [to_week setWeekOfYear:i];
            NSDate *from_now = [cal dateByAddingComponents:to_week toDate:now
                                                   options:0];
            LotteryEntry *le = [LotteryEntry new];
            //[le prepareRandomNumbers];
            [le setEntryDate:from_now];
            [mary addObject:le];
        }

        for(LotteryEntry *le in mary)
            NSLog(@"%@",le);
    }
    return 0;
}

你可能感兴趣的:(cocoa,随机数,日期格式,objC)