类的声明和实现语法
//
// main.m
// ClassDemo 类
//
// Created by ZhaiKun on 2017/10/9.
// Copyright © 2017年 ZhaiKun. All rights reserved.
//
#import <Foundation/Foundation.h>
/*
类:具有相同特征和行为的对象的集合
对象:个人的理解是 万物皆对象
*/
//类的声明
//Person 类名 首字母大写
@interface Person : NSObject
@end
//类的实现
@implementation Person
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
}
return 0;
}
类的属性/特征
//
// main.m
// ClassDemo 类
//
// Created by ZhaiKun on 2017/10/9.
// Copyright © 2017年 ZhaiKun. All rights reserved.
//
#import <Foundation/Foundation.h>
/*
类:具有相同特征和行为的对象的集合
对象:个人的理解是 万物皆对象
*/
//类的声明
//Person 类名 首字母大写
@interface Person : NSObject
{
//类的属性定义在 { } 中
NSString *name;
int age;
}
@end
//类的实现
@implementation Person
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
}
return 0;
}
类属性的调用
//
// main.m
// ClassDemo 类
//
// Created by ZhaiKun on 2017/10/9.
// Copyright © 2017年 ZhaiKun. All rights reserved.
//
#import <Foundation/Foundation.h>
/*
类:具有相同特征和行为的对象的集合
对象:个人的理解是 万物皆对象
*/
//类的声明
//Person 类名 首字母大写
@interface Person : NSObject
{
//类的属性定义在 { } 中
@public
NSString *name;
int age;
}
@end
//类的实现
@implementation Person
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *person = [Person new];//类的一个实例对象,类的每一个对象是各不相同的
//person->name = @"类属性的调用";
(*person).name = @"类属性的另一种调用方式";
NSLog(@"%@", person->name);
}
return 0;
}
类行为(方法或函数,就是某一个功能的实现)的声明、实现与调用
//
// main.m
// ClassDemo 类
//
// Created by ZhaiKun on 2017/10/9.
// Copyright © 2017年 ZhaiKun. All rights reserved.
//
#import <Foundation/Foundation.h>
/*
类:具有相同特征和行为的对象的集合
对象:个人的理解是 万物皆对象
*/
//类的声明
//Person 类名 首字母大写
@interface Person : NSObject
{
//类的属性定义在 { } 中
@public
NSString *name;
int age;
}
//方法的声明
- (void)noParamMethod;//声明一个 返回值为空void 无参数 名为noParamMethod的方法
//带有一个参数的方法
- (void)oneParamMethod:(NSString *)nameParam;//声明一个 返回值为空void 参数类型为NSString * 参数名为name 名为oneParamMethod的方法
//带多个参数的方法
- (void)paramsMethod:(int)age1 :(int)age2;
//在类方法的实现中,可以直接访问类的属性
- (int)classSelfParamMethod;
@end
//类的实现
@implementation Person
//方法的实现
- (void)noParamMethod{
NSLog(@"noParamMethod方法的实现");
}
- (void)oneParamMethod:(NSString *)nameParam{
nameParam = @"带有一个参数的方法";
NSLog(@"%@", nameParam);
}
- (void)paramsMethod:(int)age1 :(int)age2{
NSLog(@"多个参数的方法:%d", age1+age2);
}
- (int)classSelfParamMethod{
age = 18;
return age;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *person = [Person new];//类的一个实例对象,类的每一个对象是各不相同的,类中的属性和方法必须通过类的实例对象进行调用
//person->name = @"类属性的调用";
(*person).name = @"类属性的另一种调用方式";
NSLog(@"%@", person->name);
//方法的调用
[person noParamMethod];
[person oneParamMethod:@""];
[person paramsMethod:1 :2];
NSLog(@"在方法中直接调用类的属性:%d", [person classSelfParamMethod]);
}
return 0;
}