/*
程序设计目的:
实现一个通讯录,可以添加、删除、按姓名或号码排序,没有查找功能。
*/
#import"Card.h"
@implementation Card
-(id)initWithName:(NSString *)newName andNumber:(NSInteger)newNumber{
_contactName = newName;
_phoneNum = newNumber;
returnself;
}
- (void)setContactName:(NSString *)name{ _contactName = name;}
- (void)setPhoneNum:(NSInteger)number{ _phoneNum = number;}
- (NSString *)contactName{ return_contactName;}
- (NSInteger)phoneNum{ return_phoneNum;}
//按照姓名升序排列
- (BOOL)isOlderThanName:(Card *)aStudent
{
NSComparisonResult ret = [[selfcontactName] compare:[aStudentcontactName]];
if (ret == NSOrderedAscending) { returnYES;}
else {returnNO;}
}
//分号码降序排列
- (BOOL)isLowerThanNumber:(Card *)aStudent
{
if ([self phoneNum] < [aStudent phoneNum]) { returnYES;}
returnNO;
}
@end
#import"ContectBook.h"
#import"Card.h"
@implementation ContectBook
- (id)init{
_cards = [[NSMutableArray alloc] init];
return self;
}
//设置姓名
- (void)setName:(NSString *)name{_masterName = name;}
//获取姓名
- (NSString *)name{return_masterName;}
//名片:
- (void)addCard:(Card *)card{ [_cardsaddObject:card];}
//删除名片
- (void)removeCard:(Card *)card{ [_cardsremoveObject:card];}
- (void)showPhoneBook{
for (id objin _cards) {
NSLog(@" %@",[objcontactName]);
NSLog(@"Name:%@ Number:%li",[objcontactName],[obj phoneNum]);
}
}
- (void)sortedBycontactName{ [_cardssortUsingSelector:@selector(isOlderThanName:)];}
- (void)sortedByPhoneNumber{ [_cardssortUsingSelector:@selector(isLowerThanNumber:)];}
@end
#import<Foundation/Foundation.h>
#import"Card.h"
#import"ContectBook.h"
int main(int argc,const char * argv[])
{
@autoreleasepool {
long n= random();
long p = random();
// insert code here...
NSLog(@"Hello, World!");
ContectBook *book = [[ContectBookalloc] init];
for (int i =0; i<10; i++) {
p =random();
n= random();
Card *newcard = [[Cardalloc] initWithName:[NSStringstringWithFormat:@"name_%li",n]andNumber:p];
//添加:
[bookaddCard:newcard];
}
//显示明信片:
NSLog(@"显示添加的原始明信片:\n\n");
[bookshowPhoneBook];
//按照电话号码大小“降序”排序:
NSLog(@"按照电话号码大小“降序”排序:\n\n");
[booksortedByPhoneNumber];
[bookshowPhoneBook];
//按照名称“升序”排序:
NSLog(@"按照名称“升序”排序:\n\n");
[booksortedBycontactName];
[bookshowPhoneBook];
//删除名片:由于联系人是通过random随记生成的,具有不可预测性,所以删除名片功能实际是不能在这个程序中使用的,但是方法还是需要写出来
// [book removeCard:<#(Card *)#>];
}
return 0;
}