构造方法的初认识
#import <Foundation/Foundation.h>
#import "Apple.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Apple *app = [[Apple alloc] init];
Apple *apple = [Apple alloc];
Apple *appleInit = [apple init];
NSLog(@"%d",apple->_count);
// 一个对象只有一个初始化方法,调用一次之后不能再次调用
Apple *apple1 = [[Apple alloc] initWithCount:20];
Apple *a = [apple1 initWithCount:200];
Apple *b = [apple1 init];
NSLog(@"%d",b->_count);
Apple *apple2 = [[Apple alloc] initWithCount:100];
NSLog(@"%d",apple2->_count);
}
return 0;
}
#import <Foundation/Foundation.h>
@interface Apple : NSObject
{
@public;
int _count;
}
// id 万能指针可以指向任何类型
// 构造函数
// 1. 无参构造函数
- (instancetype)init;
// 2.有参的构造函数
- (instancetype)initWithCount:(int)count;
@end
#import "Apple.h"
@implementation Apple
- (instancetype)init
{
// self 当前对象
// super 当前类的父类
// [super init] 初始化父类
// 1. 加载父类资源
if (self = [super init]) {
// 初始化对象
// 2.加载自己的资源
_count = 10;
}
// 3. 资源加载完成返回
return self;
}
- (instancetype)initWithCount:(int)count
{
if (self = [super init]) {
_count = count;
}
return self;
}
@end
构造函数
#import <Foundation/Foundation.h>
#import "Apple.h"
#import "Human.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 获取苹果对象
Apple *apple10 = [[Apple alloc] initWithCount:10];
Apple *apple20 = [[Apple alloc] initWithCount:20];
// 获取人对象
Human *xiaoMing = [[Human alloc] initWithApple:apple10];
Human *xiaoHuang = [[Human alloc] initWithApple:apple20];
// 以后获取对象必须调用构造函数
Human *xxx = [[Human alloc] init];
// 计算结果
int count = xiaoMing->_apple->_count + xiaoHuang->_apple->_count;
}
return 0;
}
#import "Apple.h"
@implementation Apple
- (instancetype)initWithCount:(int)count
{
if (self = [super init]) {
_count = count;
}
return self;
}
@end
#import <Foundation/Foundation.h>
#import "Apple.h"
@interface Human : NSObject
{
@public;
Apple *_apple;
}
- (instancetype)initWithApple:(Apple *)apple;
@end
#import "Human.h"
@implementation Human
- (instancetype)initWithApple:(Apple *)apple
{
if (self = [super init]) {
_apple = apple;
}
return self;
}
@end