当前位置: 首页>编程语言>正文

Objective-c

一、创建Objective-C的测试工程
1、启动Xcode
2、创建工程
File->Create a New Project(File->New Project)->Mac OS X->Application->Command Line Tool->Type->Foundtion
3、创建新类
File->New File->Mac OS X->Cocoa Class->Objective-C class
二、类的声明
1、导入声明文件
#import <Foundation/Foundation.h>
#import <AppKit/Appkit.h>
#import <CoreData/CoreData.h>
#import “文件名.h”
2、类的声明
@interface 类的名称:继承的父类的名称
@end

eg:@interface MyObject:NSObject
@end
3、实例变量的声明
@interface MyObjcect:NSObject
{
int count;
int index;
}
@end
4、实例方法的声明
1)无参数的方法 2)一个参数的方法 3)多个参数的方法
@interface MyObjcect:NSObject
{
int count;
int index;
}
//-(返回值类型)方法名;
-(int)count;
//-(返回值类型)函数名;(参数类型)参数名;
-(void)setCount:(int)count;
//-(返回值类型)函数名;(参数类型)参数名 标签(参数类型)参数名;
-(void)setCount:(int)count andIndex:(int)index;
@end
4、类方法
@interface MyObjecet:NSObject
…………
+(int)maxIndexValue;
@end
三、编写类的的实体
类的实体代码由@implementation命名开始,与#import命令一起
#import “MyObject.h”
@implementation MyObject
@end
1、编写方法代码
#import “MyObject.h”
@implementation MyObject
-(int)count
{
return count;
}
@end
2、关于方法的声明
四、对象专用变量类型
1、id类型
2、nil类型
对象专用的变量,当其没有任何对象时,其值为nil;
NSString *string;
String=nil;
3、在条件表达式中使用对象变量
NSString *string;
//从某处取得string对象
…………
//判断string对象是否有效
if(string){ //string对象有效时的处理
}else{ //string对象无效时的处理 }
五、方法调用
1、实例方法的调用
MyObject *object;
//将MyObject实例化
MyObject *object=[[MyObject alloc]init];

//将MyObject实例化后进行自动释放
MyObject *object=[[[MyObject alloc]init]autorelease];

//调用count方法
返回值=[实例 方法名];
[object setCount:10];
[object setCount:12 andIndex:6];
2、类方法的调用
int maxIndex;
maxIndex=[MyObject maxIndexValue];
3、对象为nil的情况下
当对nil进行方法调用时,不管类型如何,都返回0
六、命名规则
1、类的命名规则
1)类名第一字母大写 2)同一工程中类名使用相同的开头
2、实例变量的命名规则
1)以小写字母开头 2)命名以下划线开始的变量时应小心
3、方法的命名规则
1)以小写字母开头
2)关于取值与设置专用方法的命名
3)以完整的英语句子命名
七、重新解析Cocoa的Hello World 程序
AppController.h
#import <Cocoa/Cocoa.h>
@interface Appcontroller:NSObjecet
{
IBOutlet id textFiled;
}
-(IBAction)sayHello:(id)sender;
@end
AppController.m
#import “Appcontroller.h”
@implementation Appcontroller
-(IBAction)sayHello:(id)sender
{
[textField setStringValue:@“Hello World!”];
}
@end
 


https://www.xamrdz.com/lan/5z61987291.html

相关文章: