objective-C第十五章课后练习答案

来源:互联网 发布:在职法律硕士 知乎 编辑:程序博客网 时间:2024/05/18 19:42

第一题

#import "ElapsedDays.h"@implementation ElapsedDays-(unsigned long) elapsedDays:(NSDate *) theDate;{        unsigned long counts;        NSDate *NowToday=[NSDate date];        counts=NowToday.timeIntervalSince1970-theDate.timeIntervalSince1970;        counts/=(60*60*24);        return counts;}@end

#import <Foundation/Foundation.h>#import "ElapsedDays.h"int main(int argc, const char * argv[]) {    @autoreleasepool { ElapsedDays *Interval=[[ElapsedDays alloc]init];        NSDateFormatter *formatter2=[[NSDateFormatter alloc]init];             [formatter2 setDateFormat:@"YYYY-MM-dd HH-mm-ss"];        NSDate *date3=[formatter2 dateFromString:@"2015-05-10 18:23:03"];        NSLog(@"%@",date3);        unsigned long day=[Interval elapsedDays : date3 ];        NSLog(@"%lu",day);        NSDate *dateNow=[NSDate date];        NSLog(@"%@",dateNow);    }    return 0;}

第二题、

第二问我用了几种方法进行的排序,选其一即可

-(void) lookup2:(NSString *)theName{    AddressBook *kolook=[[AddressBook alloc]init];    int i;    AddressCard *cc=NULL;    for(i=0;i<_book.count;i++)    {        cc=_book[i];        if ([kolook stringContentString:cc.name subString:theName])            NSLog(@" the name has in %@",cc.name);    }}
-(void) sort{    NSArray *sortedString=[_book sortedArrayUsingSelector:@selector(compareName:)];     _book=(NSMutableArray *)sortedString;}-(void) sort1{    [_book sortUsingSelector:@selector(compareName:)];}-(void) sort2{    for (NSUInteger i=0; i<_book.count; )    {        NSIndexSet *sortedString=        [_book indexesOfObjectsPassingTest:                ^(id obj1 , NSUInteger idx1, BOOL *stop)                {                    if(idx1>i)                    {                                            if ([obj1 compareName:_book[i]]==NSOrderedAscending)                        {                            NSLog(@"%@____%@",((AddressCard *)obj1).name,((AddressCard *)_book[i]).name);                            *stop=YES;                            return YES;                        }                        else                            return NO;                    }                    return NO;                }        ];        NSLog(@"______%lu____%lu",sortedString.count,sortedString.firstIndex);        if(sortedString.count!=0)        {            NSLog(@"SWAP");            id temp=nil;            temp=_book[i];            _book[i]=_book[sortedString.firstIndex];            _book[sortedString.firstIndex]=temp;        }        else{            i++;        }    }    }-(void) sort3{    NSUInteger i;    NSUInteger j;    NSUInteger min=0;    id temp=nil;        for (i=0; i<_book.count-1; i++)    {        min=i;        for (j=i+1; j<_book.count; j++)        {            if ([_book[min] compareName:_book[j]]==NSOrderedDescending)                min=j;        }        if (min!=i)        {            temp=_book[i];            _book[i]=_book[min];            _book[min]=temp;        }    }}

第三题、

-(AddressCard *) lookup3:(NSString *)theName{        for(int i=0;i<_book.count;i++)    {        if ([self stringContentString:((AddressCard *)_book[i]).name subString:theName])        {            if ((AddressCard *)_book[i]!=nil) {                [(AddressCard *)_book[i] print];            }        }    }    return nil;}(第2问)-(NSMutableArray *)sort5{    NSArray *result=[_book sortedArrayUsingSelector:@selector(compareName:)];                   _book=(NSMutableArray *)result;    return _book;}


第四题 第五题

#import <Foundation/Foundation.h>#import "AdressCard.h"@interface AdressBook : NSObject@property (nonatomic,copy) NSString * bookName;@property (nonatomic,strong)NSMutableArray *book;-(id) initWithName:(NSString *)name;-(void) addCard:(AdressCard *)theCard;-(unsigned long int)entries;-(void) list;-(AdressCard *) lookup03:(NSString *)theName;@end

#import "AdressBook.h"@implementation AdressBook-(id) initWithName:(NSString *)name{    self=[self init];    if (self)    {        _bookName=[NSString stringWithString:name];        _book=[NSMutableArray array];    }    return self;}-(void) addCard:(AdressCard *)theCard{    [_book addObject:theCard];}-(unsigned long int)entries{    return [_book count];}-(void) list{    NSLog(@"===%@ adresscard contents of ====",_bookName);    for(AdressCard *thecard in _book)        NSLog(@"%s--%s--%s--%s--%s",[thecard.surName UTF8String],              [thecard.Name UTF8String],[thecard.email UTF8String],              [thecard.Adress UTF8String],[thecard.phoneNumber UTF8String]);    NSLog(@"=====================================");}-(NSMutableArray *) lookup03:(NSString *)theName{    NSMutableArray *newArray=[NSMutableArray array];    AdressCard *nextCard;    for(nextCard in _book)    {      NSRange setrange=[[nextCard index] rangeOfString:theName options:NSCaseInsensitiveSearch];        if (setrange.location!=NSNotFound)        {                       [newArray addObject:nextCard];        }    }    return newArray;}@end

#import <Foundation/Foundation.h>@interface AdressCard : NSObject@property NSString *surName,*Name,*email,*Adress,*phoneNumber,*index;-(void)print;-(AdressCard *)initWithSetSurName:(NSString *)thesurName andName:(NSString *)   theName andEmail:      (NSString *)theEmail andAdress:(NSString *)theAdress andphoneNumber:(NSString*)thephoneNumner;-(void) buildindex;@end

#import "AdressCard.h"@implementation AdressCard-(void)print{    NSLog(@"==================");    NSLog(@"|| %s  ||",[self.surName UTF8String]);    NSLog(@"|| %s  ||",[self.Name UTF8String]);    NSLog(@"|| %s  ||",[self.email UTF8String]);    NSLog(@"|| %s  ||",[self.Adress UTF8String]);    NSLog(@"|| %s  ||",[self.phoneNumber UTF8String]);    NSLog(@"==================");}-(AdressCard *)initWithSetSurName:(NSString *)thesurName andName:(NSString *)theName andEmail:(NSString *)theEmail andAdress:(NSString *)theAdress andphoneNumber:(NSString*)thephoneNumner    {        self=[super init];        if (self) {            _surName=thesurName;            _Name=theName;            _email=theEmail;            _Adress=theAdress;            _phoneNumber=thephoneNumner;            [self buildindex];        }        return self;    }-(void) buildindex{    _index=_surName;    _index=[_index stringByAppendingString:_Name];    _index=[_index stringByAppendingString:_email];    _index=[_index stringByAppendingString:_Adress];    _index=[_index stringByAppendingString:_phoneNumber];    }@end


#import <Foundation/Foundation.h>#import "AdressCard.h"#import "AdressBook.h"int main(int argc, const char * argv[]) {    @autoreleasepool {        AdressCard *card1=[[AdressCard alloc]                            initWithSetSurName:@"di"                            andName:@"dingming"                            andEmail:@"swie@123.com"                            andAdress:@"dinlu1hao"                            andphoneNumber:@"1234567"                           ];        AdressCard *card2=[[AdressCard alloc]                           initWithSetSurName:@"ai"                           andName:@"aingming"                           andEmail:@"swie@123.com"                           andAdress:@"sinlu1hao"                           andphoneNumber:@"1234567"                           ];        AdressBook *myBook=[[AdressBook alloc]initWithName:@"zhangshan"];        NSMutableArray *foundCard;                [myBook addCard:card1];        [myBook addCard:card2];        NSLog(@"mybook count is %lu",[myBook entries]);        [myBook list];        foundCard=(NSMutableArray *)[myBook lookup03: @"ming"];        if ([foundCard count] !=0)        {            NSLog(@"i found %lu ge ",[foundCard count]);            for(AdressCard *fCard in foundCard)                [fCard print];        }        else            NSLog(@"not found");        }    return 0;}

第六题、

-(BOOL) removeName:(NSString *)theName{    NSIndexSet *result=[_book indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop)    {        if ([[[obj surName] lowercaseString] rangeOfString: [theName lowercaseString]].location!=NSNotFound)            return YES;        else            return NO;    }];    if ([result count]==1)    {        [_book removeObjectAtIndex:[result firstIndex]];        return YES;    }        else            return NO;}


第七题、

@implementation Fraction-(void) setTo:(int)n over:(int)d;{    _numerator=n;    _denominator=d;    }-(void) reduce;{    int u=_numerator;    int v=_denominator;    int temp;    while (v!=0) {        temp=u%v;        u=v;        v=temp;    }    _numerator/=u;    _denominator/=u;}-(double) convertToNum;{    if ( _denominator !=0)        return (double) _numerator/_denominator;    else        return NAN;}-(void) print;{    NSLog(@"%i/%i",_numerator,_denominator);    if (_numerator>_denominator)        NSLog(@"%i %i/%i",_numerator/_denominator,_numerator-_denominator,_denominator);    }-(NSString *) description{    return [NSString stringWithFormat:@"%i/%i",_numerator,_denominator];}@end

#import <Foundation/Foundation.h>#import "Fraction.h"int main(int argc, const char * argv[]) {    @autoreleasepool {        NSMutableArray *myArray=[NSMutableArray arrayWithCapacity:2];        NSString *s;        Fraction *f1=[[Fraction alloc]init];        Fraction *f2=[[Fraction alloc]init];        Fraction *f3=[[Fraction alloc]init];                [f1 setTo:3 over:5];        [f2 setTo:2 over:5];        [f3 setTo:1 over:4];                [myArray addObject:f1];        [myArray addObject:f2];        [myArray addObject:f3];                NSLog(@"%@",myArray);        //转化成字符串输出并以逗号隔开;        s=[myArray componentsJoinedByString:@","];        NSLog(@"%@",s);                //常规的for循环;        for (NSUInteger i=0; i<myArray.count; i++) {            NSLog(@"%@",myArray[i]);        }               //快速迭代        for (NSMutableArray *nextarray in myArray)        {            NSLog(@"%@",nextarray);        }                //使用%@        NSLog(@"%@",myArray);    }    return 0;}

第八题、

-(NSComparisonResult)comparison:(Fraction *)f{    NSNumber *selfFrac = [NSNumber numberWithFloat: [self convertToNum]];    NSNumber *fFrac=[NSNumber numberWithFloat: [f convertToNum]];       // return [selfFrac compare: fFrac];或者下面的实现方式    if ([selfFrac isLessThan:fFrac])        return NSOrderedAscending;    if([selfFrac isEqualTo:fFrac])        return NSOrderedSame;    else        return NSOrderedDescending; }   

第九题、

#import "Song.h"@implementation Song-(id)initwithSetName:(NSString *)theMusicName addArtist:(NSString *)theArtist addAlbum:(NSString *)theAlbum addMusicLength:(NSString *)theMusicLength{    if ([super init]) {    _MusicName=theMusicName;    _Artist=theArtist;    _Album=theAlbum;    _MusicLength=theMusicLength;    }    return self;}-(void)print{    NSLog(@"the song all inference:");    NSLog(@"%4s/ %4s/ %4s /%4s",[_MusicName UTF8String],[_Artist UTF8String],[_Album UTF8String],[_MusicLength UTF8String]);}

#import "Playlist.h"@implementation Playlist-(id)initwithSet:(NSString *)thePlaylistName{        if ([super init]) {    _PlaylistName=[[NSString alloc]initWithString: thePlaylistName];    _MusicSet=[NSMutableArray array];    }    return self;}-(id) init{    return [self initwithSet:@"NoName"];}-(void)add:(Song *)thesong{    [_MusicSet addObject:thesong];}-(void)remove:(Song *)thesong{    [_MusicSet removeObjectIdenticalTo:thesong];}-(void)list{    NSLog(@"**%@ playlist contents**",_PlaylistName);    for(Song *thesongs in _MusicSet)        NSLog(@"%4s--%4s--%4s--%4s",[thesongs.MusicName UTF8String],[thesongs.Artist UTF8String],[thesongs.Album UTF8String],[thesongs.MusicLength UTF8String]);    NSLog(@"***************************");}@end

#import "MusicCollection.h"#import "Playlist.h"@implementation MusicCollection-(id)init{    self=[super init];    if (self) {        _library=[[Playlist alloc]initwithSet:@"library"];        _allplaylists=[[NSMutableArray alloc]init];            }    return self;}-(void)addplaylist:(Playlist *)p{    [_allplaylists addObject:p];    for(Song *thesong in p.MusicSet)        if (![_library.MusicSet containsObject:thesong]) {            [_library add:thesong];        }}-(void)addSongToLibrary:(Song *)s andToPlaylist:(Playlist *)p{    if (![_library.MusicSet containsObject:s])        [_library.MusicSet addObject:s];    [p.MusicSet addObject:s];    }-(void)removeplaylist:(Playlist *)p{    if([_allplaylists containsObject:p])    [_allplaylists removeObject:p];    }-(void)listthemusic{        NSLog(@"^^^%@^^^",_library.PlaylistName);    for(Playlist *nextplaylist in _allplaylists)        NSLog(@"~~~%s",[nextplaylist.PlaylistName UTF8String]);}-(void) deleteSong:(Song *)s{    if ([_library.MusicSet containsObject:s])        [_library remove:s];    for(Playlist *nextplaylist in _allplaylists)        [nextplaylist remove:s];}-(void)lookup:(NSString *)theMusicName{    NSMutableArray *result=[NSMutableArray array];    Playlist *templist=[[Playlist alloc]initwithSet:[NSString stringWithFormat:@"%@",theMusicName]];    for(Song *nextsong in _library.MusicSet)    {       if ([nextsong.MusicName rangeOfString:theMusicName options:NSCaseInsensitiveSearch].length!=0)        {            [result addObject:nextsong];             continue;        }        if ([nextsong.Artist rangeOfString:theMusicName options:NSCaseInsensitiveSearch].length!=0)        {            [result addObject:nextsong];            continue;        }        if ([nextsong.Album rangeOfString:theMusicName options:NSCaseInsensitiveSearch].length!=0)        {            [result addObject:nextsong];            continue;        }        if ([nextsong.MusicLength rangeOfString:theMusicName options:NSCaseInsensitiveSearch].length!=0)        {            [result addObject:nextsong];            continue;        }        }    for (Song * tempsong in result)        [templist add:tempsong];        [templist list];}@end

int main(int argc, const char * argv[]) {    @autoreleasepool {        Song *song1=[[Song alloc]initwithSetName:@"niwo" addArtist:@"chen xiao" addAlbum:@"shendiao" addMusicLength:@"4:46"];        Song *song2=[[Song alloc]initwithSetName:@"zuimei" addArtist:@"wu qi" addAlbum:@"niai" addMusicLength:@"4:35"];        Song *song3=[[Song alloc]initwithSetName:@"meiren" addArtist:@"li linyu" addAlbum:@"zhuanji" addMusicLength:@"4:02"];        Song *song4=[[Song alloc]initwithSetName:@"zhengui" addArtist:@"wang l" addAlbum:@"zanuanji" addMusicLength:@"3:46"];        Song *song5=[[Song alloc]initwithSetName:@"niwo" addArtist:@"xiao tao" addAlbum:@"wanluo" addMusicLength:@"2:15"];        Song *song6=[[Song alloc]initwithSetName:@"nitgo" addArtist:@"xwefo tao" addAlbum:@"waseco" addMusicLength:@"2:15"];        Playlist *rock=[[Playlist alloc]initwithSet:@"my rock"];        Playlist *indie=[[Playlist alloc]initwithSet:@"my indie"];        MusicCollection *myMusic=[[MusicCollection alloc]init];        [myMusic addplaylist:indie];        [myMusic addplaylist:rock];                [myMusic addSongToLibrary:song1 andToPlaylist:rock];        [myMusic addSongToLibrary:song2 andToPlaylist:rock];        [myMusic addSongToLibrary:song3 andToPlaylist:rock];        [myMusic addSongToLibrary:song4 andToPlaylist:indie];        [myMusic addSongToLibrary:song5 andToPlaylist:indie];        [myMusic addSongToLibrary:song6 andToPlaylist:nil];        [rock remove:song1];        NSLog(@"song1 has remove.");        [rock list];        NSLog(@" no remove  song1");        [myMusic.library list];                [myMusic deleteSong:song1];        NSLog(@"song1 delete from library");        [myMusic.library list];        NSLog(@"song1 has remove alllist");        [indie list];                NSLog(@"lookup:-----");        [myMusic lookup:@"niwrd"];         [myMusic listthemusic];    }    return 0;}


第十题、

#import <Foundation/Foundation.h>#define INTOBJ(v) [NSNumber numberWithInteger:v]int main(int argc, const char * argv[]) {    @autoreleasepool {       NSArray *myArray=[NSArray arrayWithObjects:                         INTOBJ(1),INTOBJ(2),                         INTOBJ(4),INTOBJ(3),                         INTOBJ(2),INTOBJ(7),                         INTOBJ(2),INTOBJ(11),                         INTOBJ(6),INTOBJ(9),                         INTOBJ(6),INTOBJ(4),                         nil];NSCountedSet *mySet=[[NSCountedSet alloc]initWithArray:myArray];        for(NSNumber *theNumber in mySet)            NSLog(@"Obj=%li, Count=%li",(long)[theNumber integerValue],                  (long)[mySet countForObject:theNumber]);








0 0
原创粉丝点击