本分类文章想要阅读好,那么至少你要学过一点点的计算机语言,比如:C、C++、Java以及C#等等。否则,可能不知道我再说什么。实际上,我是以给自己看为主可能不会太顾及其他读者的感受,见谅。
1. Hello World:
和别的程序一样,首先是看Hello world代码:
#import <Foundation/Foundation.h> // 引入头文件, #import可以保证头文件只被包含一次
int main ( int argc, const char* argv[] ) // 主函数入口
{
NSLog(@"Hello , Objective-C !"); // NSLog:控制台输出语句,@符号:表示引用的字符串作为NSString类型来处理
// NSLog可以接收参数,如:
// int t = 12;
// NSLog(@"tt=%d",t);
return 0;
}
2. 和其他语言不一样的类型 BOOL类型:
BOOL有两个值:YES 和 NO。
YES = 1
NO = 0
注意:Objective-C的BOOL被认作是一个8位的二进制数来处理,但是却只有低位字节起作用,假如赋给BOOL型变量的值是长于1字节的整形值,并且恰好低位字节为0,那么该BOOL变量的实际值为NO。
3. Objective-C的面向对象的基础知识
3.1 间接:间接可以使代码变得容易维护,易于扩展。
3.1.1 变量
变量是一种间接。例如:
[1]
int i;
for( i=1; i<5; i++)
[2]
int i,count=5;
for(i=1; i<count; i++)
[2] 的count变量的声明以及使用就是一种间接。
3.1.2 文件
文件是一种间接。例如:
#inprot <Foundation/Foundation.h>
int main ( int argc, const char* argv[] )
{
FILE *wordFile = fopen ( “/temp/words.txt”, “r” ); //只读形式打开文件
char word[100];
while ( fgets( word, 100, wordFile) ) //循环读取每一行内容给word数组
{
word[ strlen(word) - 1 ] = '/0';
NSLog (@" %s is %d characters long", word, strlen(word) );
}
fclose(wordFile); //关闭文件
return (0);
} //main
3.1.3 类
类是一种间接。
Objective-C中关于类的声明以及使用,有点类似C++,由*.h头文件声明类,由*.m文件实现类。例如:
// Circle.h 文件:
@interface Circle : NSObject // 用@interface 来声明一个类开始,Circle继承于NSObject类型。
{
ShapeColor fillColor; // 类变量声明在类的大括号内,默认为protected。
ShapeRect bounds;
}
- (void) setFillColor : (ShapeColor) fillColor ; // 类的方法声明在大括号外,,”-”符号表示方法为对象方法;”+”符号表示方法为类方法(static)。
- (void) setBounds : (ShapeRect) bounds ;
- (void) draw ;
@end // 用@end来结束类的声明
// Circle.m 文件:
@implementation Circle //实现类的开始:@implementation,不使用大括号
- (void) setFillColor : (ShapeColor) c
{
fillColor = c; // 如果形参和类变量名称相同,则必须使用self(类似this指针)来呼叫类变量
}
- (void) setBounds : (ShapeRect) b
{
bounds = b;
}
- (void) draw
{
NSLog( @"Drawing a circle at ( %d %d %d %d ) in %@",
bounds.x,
bounds.y,
bounds.width,
bounds.height,
colorName( fillColor ) );
}
@end
//使用类:main.m
#inprot <Foundation/Foundation.h>
int main ( int argc, const char* argv[] )
{
id shape; // id:相当于Object* 指针,可以代表任何从NSObject衍生来的类型的指针。
ShapeRect rect = { 0 , 0, 20, 30 };
shape = [Circle new]; // 创建Circle对象,实际上一般常用的形式为 [[Circle alloc] init];
[shape setBounds: rect ]; // 对象方法的使用
[shape setFillColor: kRedColor];
[shape draw];
return (0);
} //main