OC5_构造方法与self指针

//
// Dog.h
// OC5_构造方法与self指针
//
// Created by zhangxueming on 15/6/9.
// Copyright (c) 2015年 zhangxueming. All rights reserved.
// #import <Foundation/Foundation.h> @interface Dog : NSObject
{
NSString *_name;
NSInteger _age;
}
//必须以 initWithXXX开头
//在一个类里面可以有多个构造方法, 但是一个对象只可以调用一次构造方法 //无参数
- (id)init;//返回对象的地址 //带一个参数
- (id)initWithName:(NSString *)name;
- (id)initWithAge:(NSInteger)age; //带两个参数
- (id)initWithName:(NSString *)name andAge:(NSInteger)age; //getter方法
- (NSString *)name; - (NSInteger)age; //setter方法
- (void)setName:(NSString *)name andAge:(NSInteger)age; //类方法
+ (void)testDog; @end
//
// Dog.m
// OC5_构造方法与self指针
//
// Created by zhangxueming on 15/6/9.
// Copyright (c) 2015年 zhangxueming. All rights reserved.
// #import "Dog.h" @implementation Dog - (instancetype)init
{
if (self = [super init]) {//引用父类方法的编译器符号
}
return self;
} - (id)initWithName:(NSString *)name
{
if (self = [super init]) {
_name = name;
}
return self;
} - (id)initWithAge:(NSInteger)age
{
if (self = [super init]) {
_age = age;
}
return self;
} - (id)initWithName:(NSString *)name andAge:(NSInteger)age
{
if(self = [super init])
{
_name = name;
_age = age;
}
return self;
} - (NSString *)name
{
return _name;
} - (NSInteger)age
{
return _age;
} - (void)setName:(NSString *)name andAge:(NSInteger)age
{
_name = name;
_age = age;
} +(void)testDog
{
Dog *xiaoHei = [[self alloc] initWithName:@"小黑" andAge: ];
NSLog(@"name = %@ age = %li", [xiaoHei name], [xiaoHei age]);
} @end
//
// main.m
// OC5_构造方法与self指针
//
// Created by zhangxueming on 15/6/9.
// Copyright (c) 2015年 zhangxueming. All rights reserved.
// #import <Foundation/Foundation.h>
#import "Dog.h"
//1.#ifndef "Dog.h" #define "Dog.h" #endif,防止头文件被重定义
//2.@class 打断循环链 防止循环包含 int main(int argc, const char * argv[]) {
@autoreleasepool {
[Dog testDog]; Dog *xiaoBai = [[Dog alloc] init];
[xiaoBai setName:@"小白" andAge:];
NSLog(@"name = %@ age = %li", [xiaoBai name], [xiaoBai age] ); }
return ;
}
上一篇:LearnMVC5-AddController


下一篇:HZAU2018年十大阅读之星演讲稿