Objective-C 学习笔记(1)

时间:2023-03-08 19:59:01
Objective-C 学习笔记(1)

文件描述:

.h 类的声明文件,用户声明变量、函数(方法)

.m 类的实现文件,用户实现.h中的函数(方法)

类的声明使用关键字 @interface、@end

类的实现使用关键字@implementation、@end

Code:

------------------------------------

项目文件:

(OS X  -> Command Line Tool)

  main.m

  student.h

  studen.m

 //
// main.m
// OC的类学习
//
// Created by loong on 14-10-25.
// Copyright (c) 2014年 loong. All rights reserved.
// #import <Foundation/Foundation.h> #import "student.h" int main(int argc, const char * argv[]) {
@autoreleasepool { // 创建一个对象
// [student alloc] 调用student类中的 alloc 静态函数
// [[student alloc] init] 在返回的类型中再次调用 init 函数
student* std = [[student alloc] init];
[std setAge:];
int age = [std age]; NSLog(@"age is: %i", age); [std setNo: :]; NSLog(@"age is: %i,no is: %i", [std age], [std no]);
//[std release];
}
return ;
}
 //
// student.h
// OC的类学习
//
// Created by loong on 14-10-25.
// Copyright (c) 2014年 loong. All rights reserved.
// // 导入头文件
#import <Foundation/Foundation.h> // .h 文件只是用来声明那些变量和函数
// @interface 声明一个类
@interface student: NSObject { // 成员变量要声明在下面的大括号中 {}
int _age; // 成员变量使用_开头
int _no;
} // age的get方法
// - 代表动态方法、 + 代表静态方法 (static)
- (int) age;
- (void) setAge:(int)age; // 同时设置两个参数
- (int) no;
- (void) setNo:(int)age : (int) no; @end
 //
// student.m
// OC的类学习
//
// Created by loong on 14-10-25.
// Copyright (c) 2014年 loong. All rights reserved.
// #import "student.h" @implementation student - (int) age {
return age;
} - (void) setAge:(int) newAge {
age =newAge;
} // =========== - (int) no {
return no;
}
- (void) setNo:(int)newAge :(int)newNo {
age = newAge;
no = newNo;
}
@end

// PS: 在 oc 中关于 . 的描述(解释)

student.age  等同于 [student getAge]

student.age = 5; 等同于 [student setAge:5]