您的位置:首页 > 职场人生

黑马程序员——OC基础语法

2015-01-18 19:54 197 查看
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------


一. 基本概念

   1. OC中没有命名空间机制,也没有包的概念,为了区分不同的类,在类名前加前缀

    2. OC中的关键字都以@开头,用于区分C和C++的关键字,字符串也以@开头,比如:

二.  面向对象

   [b] 1. @interface  等于C++/Java中的class[/b]

[b]     2. 函数前面的减号-  表示对象方法[/b]

       [b]函数前面的加号+  表示类方法[/b]

     3. 函数的返回类型和参数的类型必须用括号,形参用冒号:表示
@interface Student : NSObject{
int age;
int height;
}//成员变量的声明区间,成员变量必须在此声明

- (int)age;//本来是getAge,但是OC的习惯是用变量来命名get方法
- (void)setAge:(int)newAge;
//多形参的函数写法比较特别
- (void)setAge:(int)newAge andHeight:(int)newHeight;
@end//类的结束标记,必须写

#import "Student.h"
@implementation Student

- (int)age{
return age;
}
- (void)setAge:(int)newAge{
age = newAge;
}
- (void)setAge:(int)newAge andHeight:(int)newHeight{
age = newAge;
height = newHeight;
}
@end


 4. 对象的创建和方法调用[b]:[/b]


//OC创建对象分2步,先调用静态无参函数alloc申请内存,在调用静态无参函数init初始化
//1. Student *stu = [Student alloc];//仅仅为对象分陪内存空间
//2. stu = [stu init];//真正创建对象
//以上2步一般简写为:
Student *stu = [[Student alloc] init];
//设置
[stu setAge:100];
[stu setAge:100 andHeight:50];
//获取
NSLog(@"age is %i",[stu age]);
[stu release];//对象使用完毕要释放内存


[b][b] 5. 对象的构造方法
[/b][/b]


@interface Student{
int _age;//标准写法
int _no;
}
- (void)setAge:(int)age;
- (int)age;
- (void)setNo:(int)no;
- (int)no;
//构造方法
- (id)initWithAge:(int)age andNo:(int)no;
@end

#include "Student.h"
@implementation Student

- (int)age{
return _age;
}
- (void)setAge:(int)age{
_age = age;
}
//...
//实现构造方法
- (id)initWithAge:(int)age andNo:(int)no{
//以下写法不严谨
//self = [super init];
//_age = age;
//_no = no;
if(self=[super init]){
_age = age;
_no = no;
}
return self;
}
@end




 6. @property简化set和get

        在头文件中这样声明:

@property int age;//编译器会自动补出其set和get方法

@synthesize age;//编译器会自动生成set和get方法的实现


  7. 使用@class 提高编译效率,由于在h文件中,使用include的话,是将其内容全部拷贝过来,会影响编译效率,而且对应的h文件只有有任何改动,又要重新编译,为了解决这个问题,在h文件中,如果引用了另外一个对象,则使用@class Object; 代替include语法,用于告诉编译器该对象是存在的

@class Book;
@interface Student : NSObject
@property Book *book;
@end
但是在对应的m文件中,则必须要include入Book.h了.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: