OC对象和函数
2015-11-19 22:53
459 查看
#import <Foundation/Foundation.h> @interface Car : NSObject { //成员变量 @public int wheels; int speed; } - (void)run; @end @implementation Car - (void)run { NSLog(@"%d个轮子,速度为%dkm/h的车子跑起来了!",wheels,speed); } @end void test(int w, int s) { w = 20; s = 200; } void test1(Car *newC) { newC->wheels = 5; } void test2(Car *newC) { Car *c2 = [Car new]; c2->wheels = 5; c2->speed = 300; newC = c2; newC->wheels = 6; } int main() { Car *c = [Car new]; c->wheels = 4; c->speed = 250; //test(c->wheels, c->speed); test2(c); [c run]; return 0; }
另一个程序
/*
方法和函数的区别:
1.对象方法都是以减号 - 开头
2.对象方法的声明必须写在@interface和@end之间
对象方法的实现必须写在@implementation和@end之间
3.对象方法只能由对象调用
4.对象方法归类\对象所有
函数
1.函数能写在文件中的任意位置(@interface和@end之间除外),函数归文件所有,可在对象方法中调用
2.函数调用不依赖于对象
3.
*/
#import <Foundation/Foundation.h>
//@interface跟@interface也不能嵌套,一对一
@interface Car : NSObject
{
//statoc int wheels;不能随便将成员变量当做C语言中的变量来使用
//int wheels = 4;不允许在这里初始化
@public
int wheels;
}
- (void)run;
- (void)fly;
@end
//@interface跟@implementation不能嵌套
@implementation Car //实现
- (void)run//方法也不能当做C语言的函数使用static
{
NSLog(@"%d个轮子的车跑起来了",wheels);
}
@end
int main()//类的声明一定要在main函数前面,不然无法调用,实现可在main函数后面
{
return 0;
}
相关文章推荐
- Objective-C的内省(Introspection)用法小结
- Objective-C中常用的结构体NSRange,NSPoint,NSSize(CGSize),NSRect实例分析
- Objective-C中NSNumber与NSDictionary的用法简介
- Objective-C中NSLog输出格式大全
- 全面解析Objective-C中的block代码块的使用
- Swift调用Objective-C编写的API实例
- Swift、Objective-C、Cocoa混合编程设置指南
- Objective-c代码如何移植为Swift代码 Objective-c代码转移到Swift过程介绍
- Swift调用Objective-C代码
- 以实例讲解Objective-C中的KVO与KVC机制
- objective-c中生成随机数的方法
- 在Swift中使用Objective-C编写类、继承Objective-C类
- Swift能代替Objective-C吗?
- Objective-C 消息传递机制详解
- 在一个项目中同时使用Swift和Objective-C代码混合编程的方法
- vm安装mac os x 10.7 lion
- objective-c(一)
- objective-c(二)
- objective-c(三)