FJMobilePhone.h
#import <Foundation/Foundation.h>
@interface FJMobilePhone : NSObject{
NSString *_brand;//手机牌子
double _price;//手机价格
double _screenSize;//手机屏幕大小
NSString *_color;//手机颜色
NSString *_owner;//手机主人
NSString *_number;//手机号码
NSDictionary *_contacts;//这是一个‘字典’后面会有介绍
//简单来说字典就是存储键值对的集合。这里保存的是一个号码对应一个手机主人
}
/**初始化方法*/
+ (instancetype)phoneWithBrand:(NSString *) brand owner:(NSString *)owner
number:(NSString *)number;
- (instancetype) initWithBrand:(NSString *)brand owner:(NSString *)owner
number:(NSString *)number;
/**定义一个手机打电话的方法*/
- (BOOL) call : (NSString *) otherNumber;
/**定义一个手机发短信的功能*/
- (void) sendMessage:(NSString *) message to:(NSString *) otherNumber;
@end
FJMobilePhone.m
#import "FJMobilePhone.h"
@implementation FJMobilePhone
+ (instancetype) phoneWithBrand:(NSString *)brand owner:(NSString *)owner number:(NSString *)number{
return [[self alloc]initWithBrand:(NSString *)brand owner:(NSString *)owner number:(NSString *)number];
}
- (instancetype)initWithBrand:(NSString *)brand owner:(NSString *)owner number:(NSString *)number{
if(self = [super init]){
_brand = brand;
_owner =owner;
_number = number;
_contacts = @{@"13799322422":@"鹿晗",
@"28774198274":@"大腿",
@"37597293729":@"微微",
};//这就是字典的用法 前面是键key后面是值value通过key可以找到键
}
return self;
}
- (BOOL)call:(NSString *)otherNumber{
int rate = arc4random() %10 +1;//产生一个1到10的随意数
if(rate < 7){
NSString *otherName = _contacts[otherNumber];//这里的意思是通过otherNumber找到一个otherName
//字典的索引器语法:通过key找到value,如果给定的key没有对应的value返回nil
printf("%s正在和%s煲电话粥.......\n",[_owner UTF8String],otherName?
[otherName UTF8String]:[otherNumber UTF8String]);
//[otherNumber UTF8String]由于printf是C语言的语法这里需要把C的字符串转化成OC的字符
// UTF8String就是把C的字符串转化成OC的字符
return YES;
}
return NO;
}
- (void)sendMessage:(NSString *)message to:(NSString *)otherNumber{
NSString *otherName = _contacts [otherNumber];
printf("%s给%s发送短信, 内容是: %s\n", [_owner UTF8String], otherName? [otherName UTF8String]: [otherNumber UTF8String], [message UTF8String]);
}
@end
main.m
#import <Foundation/Foundation.h>
#import "FJMobilePhone.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
FJMobilePhone *phone = [FJMobilePhone phoneWithBrand:@"oppo" owner:@"luhan" number:@"7777777"];
[phone call:@"37597293729"];
[phone sendMessage:@"I LOVE YOU" to:@"37597293729"];
}
return 0;
}
程序运行结果截图: