示例:制作地址簿

作者:追风剑情 发布于:2019-3-1 13:26 分类:Objective-C

地址卡片类 (版本一:手写存取器)

AddressCard.h

// 地址卡片
#import <Foundation/Foundation.h>

@interface AddressCard : NSObject

-(void) setName: (NSString *) theName;
-(void) setEmail: (NSString *) theEmail;
-(NSString *) name;
-(NSString *) email;
-(void) print;

@end


AddressCard.m

#import "AddressCard.h"

@implementation AddressCard
{
    NSString *name;
    NSString *email;
}

-(void) setName: (NSString *) theName
{
    if (name != theName)
        name = [NSString stringWithString: theName];
}

-(void) setEmail: (NSString *) theEmail
{
    if (email != theEmail)
        email = [NSString stringWithString: theEmail];
}

-(NSString *) name
{
    return name;
}

-(NSString *) email
{
    return email;
}

-(void) print
{
    // %-31s 表示要用31个字符的字段宽度左对齐打印UTF8 C-字符串
    NSLog(@"========================");
    NSLog(@"| %-31s  |", [name UTF8String]);
    NSLog(@"| %-31s  |", [email UTF8String]);
    NSLog(@"========================");
}

@end


====================================================================

地址卡片类 (版本二:自动生成存取器)

AddressCard.h

// 地址卡片
#import <Foundation/Foundation.h>

@interface AddressCard : NSObject

// 自动生成存取器
// copy特性: 会在setter方法内生成实例变量的副本。默认的方法不会生成副本,仅仅进行赋值(默认为assign特性)
// nonatomic特性: 确保线程安全
@property (copy, nonatomic) NSString *name, *email;

// instancetype: 告诉编译器返回的类型是发送消息的对象
-(instancetype) initWithName: (NSString *) theName andEmail: (NSString *) theEmail;
-(void) setName: (NSString *) theName andEmail: (NSString *) theEmail;
-(void) print;
-(NSComparisonResult) compareNames: (id) element;

@end


AddressCard.m

#import "AddressCard.h"

@implementation AddressCard

@synthesize name, email;

-(instancetype) initWithName: (NSString *) theName andEmail: (NSString *) theEmail
{
    self = [super init];
    if (self) {
        self.name = theName;
        self.email = theEmail;
    }
    return self;
}

-(void) setName: (NSString *) theName andEmail: (NSString *) theEmail
{
    // 会绕过setter方法
    //name = theName;
    //email = theEmail;
    
    // 调用setter方法
    self.name = theName;
    self.email = theEmail;
    // 等价于下面两句
    //[self setName: theName];
    //[self setEmail: theEmail];
}

-(void) print
{
    // %-31s 表示要用31个字符的字段宽度左对齐打印UTF8 C-字符串
    NSLog(@"====================================");
    NSLog(@"| %-31s  |", [name UTF8String]);
    NSLog(@"| %-31s  |", [email UTF8String]);
    NSLog(@"====================================");
}

// 重写相等性判断
-(BOOL) isEqual: (AddressCard *) theCard
{
    if ([name isEqualToString: theCard.name] == YES &&
        [email isEqualToString: theCard.email] == YES)
        return YES;
    else
        return NO;
}

// 比较指定的地址卡片中的两个名字
-(NSComparisonResult) compareNames: (id) element
{
    return [name compare: [element name]];
}

@end


AddressBook.h

// 地址簿
#import <Foundation/Foundation.h>
#import "AddressCard.h"

@interface AddressBook : NSObject

// strong特性:声明变量为强变量
@property (nonatomic, copy) NSString *bookName;
@property (nonatomic, strong) NSMutableArray *book;

-(instancetype) initWithName: (NSString *) name;
-(void) addCard: (AddressCard *) theCard;
-(int) entries;
-(void) list;
-(AddressCard *) lookup: (NSString *) theName;
-(void) removeCard: (AddressCard *) theCard;
-(void) sort;

@end


AddressBook.m

#import "AddressBook.h"

@implementation AddressBook

@synthesize bookName, book;

// 设置AddressBook的名称和一个空的AddressBook
-(instancetype) initWithName: (NSString *) name
{
    self = [super init];
    if (self) {
        bookName = [NSString stringWithString: name];
        book = [NSMutableArray array];
    }
    return self;
}

-(instancetype) init
{
    return [self initWithName: @"NoName"];
}

// 添加地址卡片
-(void) addCard: (AddressCard *) theCard
{
    [book addObject: theCard];
}

// 返回地址卡片数目
-(int) entries
{
    return (int)[book count];
}

-(void) list
{
    NSLog(@"======== Contents of: %@ ========", bookName);
    // 遍历地址簿,方法一
    /*for (AddressCard *theCard in book)
        NSLog(@"%-20s  %-32s", [theCard.name UTF8String],
              [theCard.email UTF8String]);*/
    
    // 遍历地址簿,方法二
    /*AddressCard *theCard;
    for (theCard in book)
        NSLog(@"%-20s  %-32s", [theCard.name UTF8String],
              [theCard.email UTF8String]);*/
    
    // 遍历地址簿,方法三
    [book enumerateObjectsUsingBlock:
     //idx 数组索引 stop 是否停止遍历
     ^(AddressCard *theCard, NSUInteger idx, BOOL *stop) {
         NSLog(@"%-20s  %-32s", [theCard.name UTF8String],
               [theCard.email UTF8String]);
     }];
    NSLog(@"===================================================");
}

// 通过名称查找地址卡片-(精确匹配)
-(AddressCard *) lookup: (NSString *) theName
{
    for (AddressCard *nextCard in book)
        if ([nextCard.name caseInsensitiveCompare: theName] == NSOrderedSame)
            return nextCard;
    
    return nil;
}

-(void) removeCard: (AddressCard *) theCard
{
    // removeObjectIdenticalTo 会删除重复对象(即,一个对象在数组中出现多次)
    [book removeObjectIdenticalTo: theCard];
}

-(void) sort
{
    // 方法一:传递一个比较方法
    //[book sortUsingSelector: @selector(compareNames:)];
    
    //[book sortUsingSelector:];//提供一个比较方法
    //[book sortUsingFunction: context:]; //提供一个比较函数
    
    // 方法二:使用区块(Block)排序
    [book sortUsingComparator:
     ^(id obj1, id obj2){
         return [[obj1 name] compare: [obj2 name]];
     }];
}

@end


main.m

#import <Foundation/Foundation.h>
#import "AddressCard.h"
#import "AddressBook.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSString *aName = @"Julia Kochan";
        NSString *aEmail = @"jewls337@axlc.com";
        NSString *bName = @"Tony Iannino";
        NSString *bEmail = @"tony.iannino@techfitness.com";
        NSString *cName = @"Stephen Kochan";
        NSString *cEmail = @"steve@classroomM.com";
        NSString *dName = @"Jamie Baker";
        NSString *dEmail = @"jbaker@classrooM.com";
        
        AddressCard *card1 = [[AddressCard alloc] init];
        AddressCard *card2 = [[AddressCard alloc] init];
        AddressCard *card3 = [[AddressCard alloc] init];
        AddressCard *card4 = [[AddressCard alloc] init];
        
        // 创建地址薄
        AddressBook *myBook = [[AddressBook alloc]
                               initWithName: @"Linda's Address Book"];
        
        AddressCard *myCard;
        
        // 创建4个地址卡片
        [card1 setName: aName andEmail: aEmail];
        [card2 setName: bName andEmail: bEmail];
        [card3 setName: cName andEmail: cEmail];
        [card4 setName: dName andEmail: dEmail];

        // 添加卡片到地址薄
        [myBook addCard: card1];
        [myBook addCard: card2];
        [myBook addCard: card3];
        [myBook addCard: card4];
        
        NSLog(@"Entries in address book after adding cards: %i", [myBook entries]);
        
        // 列出未排序的地址薄
        [myBook list];
        
        // 列出排序后的地址薄
        [myBook sort];
        [myBook list];
        
        // 通过名字查找一个人
        NSLog(@"Lookup: Stephen Kochan");
        myCard = [myBook lookup: @"Stephen Kochan"];
        
        if (myCard != nil)
            [myCard print];
        else
            NSLog(@"Not found!");
        
        // 从地址薄中删除条目
        [myBook removeCard: myCard];
        [myBook list];
    }
    return 0;
}

运行测试
111.png

标签: Objective-C

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号