@fiy-fish
2015-07-14T19:49:02.000000Z
字数 1992
阅读 1194
Objective-c
// main.m
// day02-04-扑克牌
//
// Created by Aaron on 15/7/2.
// Copyright (c) 2015年 Aaron. All rights reserved.
//
//左手和右手的扑克牌进行交换
#import <Foundation/Foundation.h>
#import "Pocker.h"
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Pocker *p1 = [[Pocker alloc] initWithName:@"♥10"];
//%@ 输出字符串对象
//NSLog(@"---%@",[p1 name]);
Person *person = [[Person alloc] init];
[person leftHandCatchPocker:p1];
//[person showPocker];
Pocker *p2 = [[Pocker alloc] initWithName:@"😎"];
[person rightHandCatchPocker:p2];
[person showPocker];
[person changePocker];
[person showPocker];
}
return 0;
}
#import <Foundation/Foundation.h>
#import "Hand.h"
@interface Person : NSObject
{
Hand *_leftHand;
Hand *_rightHand;
}
-(void)leftHandCatchPocker:(Pocker *)p;
-(void)rightHandCatchPocker:(Pocker *)p;
-(void)changePocker;
-(void)showPocker;
@end
#import "Person.h"
@implementation Person
-(instancetype)init
{
//可以不初始化么,这里初始化成了什么值
if(self = [super init])
{
_leftHand = [[Hand alloc] init];
_rightHand = [[Hand alloc] init];
}
return self;
}
-(void)leftHandCatchPocker:(Pocker *)p
{
//可以调用其他类的对象方法?
[_leftHand setMyPocker:p];//变量可以调用方法?
}
-(void)rightHandCatchPocker:(Pocker *)p
{
[_rightHand setMyPocker:p];
}
-(void)changePocker
{
Pocker *temp = [_leftHand myPocker];
[_leftHand setMyPocker:[_rightHand myPocker]];
[_rightHand setMyPocker:temp];
}
-(void)showPocker
{
NSLog(@"左手上的牌是:%@",
[[_leftHand myPocker] name]);
NSLog(@"右手上的牌是:%@",
[[_rightHand myPocker] name]);
}
@end
#import <Foundation/Foundation.h>
//记得包含“Pocker.h”头文件
#import "Pocker.h"
@interface Hand : NSObject
{
Pocker *_myPocker;// 带*号
}
-(void)setMyPocker:(Pocker *)p;
-(Pocker *)myPocker;
@end
#import "Hand.h"
@implementation Hand
-(void)setMyPocker:(Pocker *)p
{
//为什么要判断
if(_myPocker != p)
{
_myPocker = p;
}
}
-(Pocker *)myPocker
{
return _myPocker;
}
@end
#import <Foundation/Foundation.h>
@interface Pocker : NSObject
{
NSString *_name;//申明字符串一定要带*号?
}
-(instancetype)initWithName:(NSString *)name;
-(NSString *)name;
@end
#import "Pocker.h"
@implementation Pocker
-(instancetype)initWithName:(NSString *)name
{
//如果不初始化是什么后果
if(self = [super init])
{
_name = name;
}
return self;
}
-(NSString *)name
{
return _name;
}
@end